wpf - 使用 Style 在许多 WPF 元素中处理 Window 的 RoutedEvent

标签 wpf styles eventtrigger routed-events

我有以下路由事件:

public static readonly RoutedEvent FakeEvent = EventManager.RegisterRoutedEvent(
    "Fake", RoutingStrategy.Tunnel, typeof(RoutedEventHandler), typeof(MainWindow));
public event RoutedEventHandler Fake
{
    add { AddHandler(FakeEvent, value); }
    remove { RemoveHandler(FakeEvent, value); }
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    RoutedEventArgs newEventArgs = new RoutedEventArgs(MainWindow.FakeEvent);
    RaiseEvent(newEventArgs);
}

我有以下 XAML:

<Window.Resources>

    <Style TargetType="{x:Type TextBlock}"
       xmlns:local="clr-namespace:WpfApplication1">
        <Setter Property="Margin" Value="10" />
        <Setter Property="Background" Value="Red" />
        <Style.Triggers>
            <EventTrigger RoutedEvent="local:MainWindow.Fake">
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation To="Blue" Duration="0:0:1"
                            Storyboard.TargetProperty="Background.Color" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Style.Triggers>
    </Style>

</Window.Resources>

<StackPanel>
    <Button Click="Button_Click">Raise Event</Button>
    <TextBlock>Hello World</TextBlock>
    <TextBlock>Hello World</TextBlock>
    <TextBlock>Hello World</TextBlock>
    <TextBlock>Hello World</TextBlock>
    <TextBlock>Hello World</TextBlock>
    <TextBlock>Hello World</TextBlock>
</StackPanel>

我的目标是通过使用可重用的通用样式,窗口的路由事件会导致 Storyboard针对所有 TextBlock 触发。但是,引发路由事件(通过单击按钮)不会导致任何事情发生(没有错误,什么也没有)。不确定出了什么问题。

正确的做法是什么?

最佳答案

您可能误解了如何 tunneling作品:

Tunneling: Initially, event handlers at the element tree root are invoked. The routed event then travels a route through successive child elements along the route, towards the node element that is the routed event source (the element that raised the routed event).

这里事件将从根、窗口传播到源,也是窗口,它永远不会遇到 TextBlocks。您可能需要在所有事件上引发事件或在窗口上监听事件,遗憾的是您不能在样式中使用 EventTrigger.SourceName。可悲的是,我不知道有什么好的解决方案......

(您可以使用 EventSetter 来处理 TextBlocksLoaded 事件,然后监听窗口上的事件并在本地重新引发它(您将需要更改路由策略,否则如果您不检查事件的来源,您将获得堆栈溢出异常),这是否是个好主意可能值得怀疑)

关于wpf - 使用 Style 在许多 WPF 元素中处理 Window 的 RoutedEvent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9233739/

相关文章:

jquery - 我无法在 jQuery 上触发 'click' 事件

javascript - jQuery 在拖动时触发 mouseup

wpf - 绑定(bind)wpf后如何将项目插入组合框

wpf - 如何设置 UserControl 的高度和宽度

jquery - 仅更改在多个类之间单击的类具有相同名称的样式

android - 应用程序 :theme now is deprecated

Android OnInfoWindowClickListener() 从未调用过

c# - 在列表框中选择文本框项不会更改列表框的选定项

wpf 工具提示 - 设置跨应用程序的持续时间

javascript - 你如何确定 JavaScript 中的媒体类型?