将事件设置为相同类型的所有控件

Ike*_*son 3 wpf events controls

在WPF中,有一种方法可以将特定类型的事件设置为相同类型的所有控件.例如,我正在尝试在TextBlock类型的所有控件上设置MouseLeftButtonDown事件.这是我试图做的,这显然是错误的:

<Style TargetType="{x:Type TextBlock}">
    <Setter Property="MouseLeftButtonDown" Value="TextBlock_LeftClick"/>
</Style>
Run Code Online (Sandbox Code Playgroud)

有没有办法可以做到这一点?

sa_*_*213 6

是的,有一种方法,您可以使用该EventSetter属性为所有应用的样式Style设置一个EventHandlerElements

例:

<Style TargetType="{x:Type TextBlock}">
    <EventSetter Event="MouseLeftButtonDown" Handler="TextBlock_LeftClick" />
</Style>
Run Code Online (Sandbox Code Playgroud)


Sam*_*tak 6

您可以使用 WPF EventManager 在单个语句中执行此操作

EventManager.RegisterClassHandler(typeof(Hyperlink), 
                                  Hyperlink.ClickEvent, 
                                 new RoutedEventHandler(this.OnHyperlinkClick));
Run Code Online (Sandbox Code Playgroud)