3

我有以下路由事件:

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>

我的目标是通过使用可重用的通用样式,窗口的路由事件将导致情节提要为所有 TextBlock 触发。但是,引发路由事件(通过单击按钮)不会导致任何事情发生(没有错误,只是什么都没有)。不知道出了什么问题。

对此的正确方法是什么?

4

1 回答 1

2

您可能误解了隧道的工作原理:

隧道:最初,调用元素树根处的事件处理程序。然后,路由事件沿着路由穿过连续的子元素,到达作为路由事件源的节点元素(引发路由事件的元素)。

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

(您可以使用 anEventSetter来处理 to 的Loaded事件,TextBlocks然后在窗口上侦听该事件并在本地重新引发它(您将需要更改路由策略,或者如果您不检查在哪里,您将获得堆栈溢出异常事件来自),这是否是一个好主意可能值得怀疑)

于 2012-02-11T00:27:44.263 回答