我正在尝试订阅从
EventTrigger
元素中的代码隐藏触发的自定义事件。 我能找到的所有示例都是前端触发的事件,但我想反过来做。 这是一些示例代码,旨在每秒触发动画:
背后代码:
public partial class MainWindow : Window
{
public static readonly RoutedEvent RoutedEvent = EventManager.RegisterRoutedEvent(
name: "TestRoutedEventName",
routingStrategy: RoutingStrategy.Bubble,
handlerType: typeof(RoutedEventHandler),
ownerType: typeof(MainWindow));
public event RoutedEventHandler Event
{
add { AddHandler(RoutedEvent, value); }
remove { RemoveHandler(RoutedEvent, value); }
}
public MainWindow()
{
InitializeComponent();
_ = new DispatcherTimer(
TimeSpan.FromSeconds(1000),
DispatcherPriority.Normal,
(sender, args) => RaiseEvent(new RoutedEventArgs(RoutedEvent)),
App.Current.Dispatcher);
}
}
XAML:
<Window x:Class="WpfEventTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfEventTest"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="200">
<StackPanel>
<Viewbox Stretch="Fill" Width="100" Height="100">
<Canvas Width="100" Height="100">
<Path Fill="#FF0000" Name="Path">
<Path.Data>
<PathGeometry Figures="M 10 10 H 90 V 90 H 10 L 10 10" FillRule="NonZero"/>
</Path.Data>
<Path.Triggers>
<EventTrigger RoutedEvent="**WHAT DO I PUT IN HERE**">
<BeginStoryboard>
<Storyboard>
<ColorAnimation
Storyboard.TargetName="Path"
Storyboard.TargetProperty="Fill.Color"
From="Red" To="White" Duration="0:0:0.8" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Path.Triggers>
</Path>
</Canvas>
</Viewbox>
</StackPanel>
</Window>
目前,为了简单起见,我只是使用
DispatcherTimer
,但事件需要来自外部源。
问题:
RoutedEvent
绑定到 EventTrigger
?对于名称
"TestRoutedEventName"
,字段应命名为
public static readonly RoutedEvent TestRoutedEventNameEvent
,事件应命名为 public event RoutedEventHandler TestRoutedEventName
。考虑到该字段将被命名为 TestRoutedEventNameEvent
并且 NS 为
xmlns:local="clr-namespace:WpfEventTest"
,你应该用 XAML 编写:<EventTrigger RoutedEvent="{x:Static local:MainWindow.TestRoutedEventNameEvent}">
...
</EventTrigger>
要使其工作,您必须在
RaiseEvent
实例上触发事件(调用
Path
)。在窗口实例上调用 RaiseEvent
不起作用。注意:由于这是一个冒泡事件,因此在 RaiseEvent
的任何逻辑子节点上调用
Path
也可以,但 Path
不能有任何逻辑子节点。