Need help handling DataTemplate events in Application.xaml

My application has a data template with several buttons. I want these buttons, even the handler, to be launched on the current page (I use this template on many pages), and not in the Application.xaml.vb / cs file, since I want different actions on each page.

I hope I get it.

+2
source share
2 answers

To achieve this, you can use the command. Ask Button in the DataTemplate to execute specific Command s:

 <Button Command="{x:Static MyCommands.SomeCommand}"/> 

Then each view that uses the DataTemplate processes Command :

 <UserControl> <UserCommand.CommandBindings> <CommandBinding Command="{x:Static MyCommands.SomeCommand}" Executed="_someHandler"/> </UserCommand.CommandBindings> </UserControl> 

EDIT after comments: After you have created the code for your ResourceDictionary according to these instructions , you can simply connect events in the usual way:

In MyResources.xaml :

 <ListBox x:Key="myListBoxResource" ItemSelected="_listBox_ItemSelected"/> 

Then in MyResources.xaml.cs :

 private void _listBox_ItemSelected(object sender, EventArgs e) { ... } 
+2
source

If you use events, not commands, then in the Click event handler just write

 private void Button_Click(object sender, RoutedEventArgs e) { var dataItem = (FrameworkElement)sender).DataContext; // process dataItem } 
0
source

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


All Articles