views:

22

answers:

1

I have a ListBox that uses DataTemplateSelector to dynamically decide what template to use based on the type of the item in the list. I now want to hook the events that could be fired by controls within the DataTemplate. For example, if one of the templates has a checkbox in it, I want the application using the control to be notified when the checkbox is checked. If a different template has a button within it, I want to be notified when the button is clicked.

Also, since its a ListBox, many of the items could have the same template. So I will need some kind of RoutedEventArgs so I can walk up from OriginalSource to get some context information to handle the event.

My solution was to use MouseLeftButtonUp. This works fine for TextBlocks, but it looks like CheckBox and Button controls set handled to true, so the event doesnt bubble up. How can I address these events so I can assign handlers to them in my calling application?

(Also, Silverlight doesn't actually support DataTemplateSelector, so i followed this example to implement it)

A: 

If you are defining the templates in the Xaml for the user control where your event handlers are placed then you should simply be able to assign the event handlers in the Xaml.

However in the specific scenario you outline you can also listen for the MouseLeftButtonUp event via the AddHandler method:-

 myListBox.AddHandler(UIElement.MouseLeftButtonUpEvent, myListBox_MouseLeftButtonUp, true);

...

private void myListBox_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    //e.OriginalSource available for your inspection
}

Note by using AddHandler and passing true in the third parameter you will get the event regardless of whether it has been handled.

AnthonyWJones
That works, thanks! I'd like to delve into the other option: specifying the event handler in XAML. My problem here is that the XAML is part of a class library that gets referenced in the application, since i created a user control for it. How can i add an event handler in XAML if the handler is going to be in a project that will reference this project?
theraju