Accessing Elements Inside a DataTemplate in WPF

I was wondering if it is possible to get actual instances of datatemplate objects in WPF. For example, in the following situation:

<UserControl>
    <UserControl.Resources>
        <DataTemplate x:Key="MyTemplate">
            <CustomControl ></CustomControl>
        </DataTemplate>
    </UserControl.Resources>

    <ListBox DataTemplate="{StaticResource MyTemplate}"></ListBox>
</UserControl>

Suppose that CustomControlhas a CustomEventand is public CustomMethod. I want to access this event and the public method in a user control. Is it possible? How can I do this? Thanks in advance for any help.

Greetings

Nilu

+3
source share
3 answers

You need to find a ContentPresenter containing the ListBox (by navigating VisualTree) and then use

myDataTemplate.FindName("myCustomControl", myListBox);

MSDN has an example: http://msdn.microsoft.com/en-us/library/bb613579.aspx .

+5

, CustomControl .

blogpost , : ICommand Silverlight

, ( WPF ) , .

, :

<CustomControl 
  MyNamespace:CustomControlCommand.EventCommand=
  "{Binding Path=CommandHandler}" />

CustomControl, .

0

ItemsSource ListBox, , . - ObservableCollection < > , ListBox ViewModel. , .

, - , , , UserControl.

ViewModel ICommand ( , ). UserControl DataContext, ViewModel. , ViewModel .

,

MVVM, ICommands

( )

class ViewModelType {
    public void DoSomething() { /* ... */ }
    public ICommand DoSomethingCommand { get; set; }
    public string Property { get; set; }
}

class CodeBehind {
    public void EventHandler(object, args) {
        (DataContext as ViewModelType).DoSomethingElseCommand.Execute();
    }
}
0

Source: https://habr.com/ru/post/1720234/


All Articles