处理窗口';s RoutedEvent在许多WPF元素中具有样式
我有以下事件:处理窗口';s RoutedEvent在许多WPF元素中具有样式,wpf,styles,eventtrigger,routed-events,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
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>
升起事件
你好,世界
你好,世界
你好,世界
你好,世界
你好,世界
你好,世界
我的目标是,窗口的routed事件将使用可重用的通用样式为所有文本块触发故事板。但是,引发路由事件(通过单击按钮)不会导致任何事情发生(没有错误,只是什么都没有)。不知道怎么了
正确的方法是什么?您可能误解了工作原理: 隧道:最初,调用元素树根的事件处理程序。然后,路由事件沿着路由通过连续的子元素,向作为路由事件源的节点元素(引发路由事件的元素)移动路由 在这里,事件将从根、窗口传播到源,也就是窗口,它永远不会遇到
TextBlocks
。您可能需要在所有事件上引发事件,或者在窗口上侦听事件,很遗憾,您不能在样式中使用EventTrigger.SourceName
。遗憾的是,我不知道有什么好的解决办法
(您可以使用EventSetter
来处理TextBlocks
的Loaded
事件,然后侦听窗口上的事件并在本地重新引发它(您将希望更改路由策略,或者如果不检查事件的来源,您将得到堆栈溢出异常),如果这是个好主意,可能会有疑问)