Need help handling events of a DataTemplate in the

2019-07-12 20:04发布

问题:

I have in my application a data template that has a few buttons. I want those buttons' even handler to be fired in the current page (I am using this template in many pages) rather than in the Application.xaml.vb/cs file, since I want different actions on each page.

I hope I am clear.

回答1:

You can use commanding to achieve this. Have the Buttons in the DataTemplate execute specific Commands:

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

Then have each view that uses that DataTemplate handle the Command:

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

EDIT after comments: Once you have created a code-behind for your ResourceDictionary as per these instructions, you can simply connect events in the usual fashion:

In MyResources.xaml:

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

Then in MyResources.xaml.cs:

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


回答2:

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

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