event handler in DataTemplate

在user control中,给data template加event handler很容易,因为user control的xaml是与cs编译成一个类, 有x:class tag. 但是在custom control  中,必须代码加入,而且要用visual tree找到data template中的element(这是独立的dataTemplate情况),或者在onApplyTemplate中找到control,再把event handlers加入。

还有给data template中element 抛event , 外面的event handler能通过originalSource获得原始event源,但是name失去了。

总体来说,用user control 容易些,custom control 更依赖代码。但是user control密切与界面相关,不容易重写,custom control与界面相对独立,只是要求一些特定templatePart .重用性强,一般来说 有自定义content的时候就会用customcontrol

 

那么如何处理data template中的event handler,四种方法:.

1.  If the template isn't reused in multiple places, attach the handler directly to the button.
2.  Use the routed nature of events in WPF to catch the click event on an ancestor control, such as the List itself. If you have more than one button in the template, you'll have to figure out how to differentiate between sources of the event.
3.  Raise a more specific event from a click handler on the button.
4.  Use a command instead of an event.

使用一个routed command,用command parameter传入参数,是一个挺好的方法。

<Button x:Name="cmdDeleteItem" Width="59" Height="21.277" Content="Delete"
Command=”x:Static Mycontrol.deleteCommand” CommandParameter=”{Binding Id}”/>

 

posted on 2008-12-05 13:36  oyl  阅读(358)  评论(0编辑  收藏  举报

导航