2

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.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632

2 Answers2

2

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)
{
    ...
}
Community
  • 1
  • 1
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • Then how would you set some of the events in the code behind? And what if I use ResourceDictionary (that doesn't have a code behind file) and I want to refer to a handler in the ResourceDictionary page itself. – Shimmy Weitzhandler Mar 30 '09 at 15:28
  • You can easily have a code-behind file for a ResourceDictionary. See http://stackoverflow.com/questions/92100/is-it-possible-to-set-code-behind-a-resource-dictionary-in-wpf-for-event-handli – Kent Boogaart Mar 30 '09 at 15:33
  • 1) please edit the 2nd snippet regarding how to address the event to a local handler. 2) what's MyCommands, a declaration? – Shimmy Weitzhandler Mar 30 '09 at 15:52
  • 1) OK, edited. 2) You'll need to read up on commanding and routed commands in particular. – Kent Boogaart Mar 30 '09 at 16:11
  • I don't want to fire the ItemSelected event, I want to fire the event in the DataTemplate's button, since I have many button's in the template (i.e. remove, edit, move up, move down and more plenty of buttons). thanks. – Shimmy Weitzhandler Mar 30 '09 at 17:03
0

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
}
xmedeko
  • 7,336
  • 6
  • 55
  • 85