通过 Interactivity.EventTrigger 捕获自定义事件
本文关键字:自定义 事件 Interactivity EventTrigger 通过 | 更新日期: 2023-09-27 18:35:24
我有一个简单的用户控件,其中包含一个事件:
using System.Windows;
namespace TriggersTest
{
public partial class MyControl
{
public MyControl()
{
InitializeComponent();
}
public static readonly RoutedEvent ButtonPressedEvent =
EventManager.RegisterRoutedEvent("ButtonPressed", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyControl));
public event RoutedEventHandler ButtonPressed
{
add { AddHandler(ButtonPressedEvent, value); }
remove { RemoveHandler(ButtonPressedEvent, value); }
}
private void OnButtonClick(object sender, RoutedEventArgs e)
{
RaiseEvent(new RoutedEventArgs { RoutedEvent = ButtonPressedEvent });
}
}
}
我想在另一个视图中捕获此事件:
<Window x:Class="TriggersTest.MainWindow"
Name="Root"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:TriggersTest"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:MyControl>
<i:Interaction.Triggers>
<i:EventTrigger EventName="ButtonPressed">
<i:InvokeCommandAction Command="{Binding MyCommand, ElementName=Root}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</local:MyControl>
</Grid>
</Window>
事件已引发,但 i:EventTrigger 不会调用命令。
我该如何解决这个问题?
你的代码都很好。绑定不起作用。我只要看这个就知道了。
不要在 InvokeCommandAction 中使用 ElementName,因为 InvokeCommandAction 不是 WPF 中 LogicalTree 的一部分。
只需更改绑定或使用 x:引用,一切都应该没问题。