开发者

How do I hook an event to a control that comes in dynamically as part of a DataTemplate?

开发者 https://www.devze.com 2023-01-12 21:10 出处:网络
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

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 t开发者_开发技巧hese 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)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号