The ongoing software adventures of Julian Biddle

Responding To Events From DataTemplate Controls in WPF

WPF provides the ability to create templated items for controls such as the list and grid.

These item templates allow any WPF controls including labels, text areas and buttons. My problem was knowing how to create code that responds to the clicks of these buttons. Wasn’t terribly obvious to me.

to the cs file I’ve added a handler:
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(((Button) sender).CommandParameter.ToString());
}
And it worked very well thanks guys…

Laurent’s suggestion worked perfectly for me. I have a ListView on my page which uses a DataTemplate defined in a seperate ResourceDictionary. I was trying to figure out a way to respond to events of controls in the DataTemplate and using event bubbling as described was exactly what I needed. Thanks!

Laurent’s way works, but i cant figure out how to identify on which ‘row’ of my ListBox the button was clicked, where as i suspect because of the CommandParameter (i’m just about to try it) the technique in this article will.