Set an event to all controls of same type

2019-07-04 01:23发布

In WPF is there a way to set a particular type of event to all controls of the same type. For example, I'm trying to set the MouseLeftButtonDown event on all controls of type TextBlock. Here is what I tried to do which is obviously wrong:

<Style TargetType="{x:Type TextBlock}">
    <Setter Property="MouseLeftButtonDown" Value="TextBlock_LeftClick"/>
</Style>

Is there a way that this can be done?

2条回答
ゆ 、 Hurt°
2楼-- · 2019-07-04 02:02

Yes there is a way, you can use the EventSetter property in the Style to set a EventHandler for all Elements with that style applied

Example:

<Style TargetType="{x:Type TextBlock}">
    <EventSetter Event="MouseLeftButtonDown" Handler="TextBlock_LeftClick" />
</Style>
查看更多
在下西门庆
3楼-- · 2019-07-04 02:24

You can do this in a single statement using WPF EventManager

EventManager.RegisterClassHandler(typeof(Hyperlink), 
                                  Hyperlink.ClickEvent, 
                                 new RoutedEventHandler(this.OnHyperlinkClick));
查看更多
登录 后发表回答