我不想使用输入设备生成的事件,而是想使用自定义事件,该事件将在代码隐藏中以编程方式引发,作为我的 xaml 中的 EventTrigger。
这应该很容易,但我在任何地方都找不到例子。
以下是我通过学习 WPF4 Unleashed 第 6 章、路由事件实现、EventTrigger.RoatedEvent 属性、自定义 RoutedEvent 作为 EventTrigger 以及许多其他内容得出的结论:
MainWindow.xaml.cs:
namespace RoutedEventTrigger
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
RaiseEvent(new RoutedEventArgs(fooEvent, this));
}
public static readonly RoutedEvent fooEvent = EventManager.RegisterRoutedEvent(
"foo", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(MainWindow));
// Provide CLR accessors for the event
public event RoutedEventHandler foo
{
add { AddHandler(fooEvent, value); }
remove { RemoveHandler(fooEvent, value); }
}
}
}
MainWindow.xaml:
附注请温柔一点,我对 WPF 还比较陌生。
大隈斯科特,
您是否尝试过构建(重建)该项目? WPF 要求您构建项目,以便 XAML 解析器可以看到项目更改。使用下面的代码构建就可以了。
代码
public partial class MainWindow : Window
{
public MainWindow() => InitializeComponent();
public static readonly RoutedEvent fooEvent = EventManager.RegisterRoutedEvent("foo",
RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(MainWindow));
// Provide CLR accessors for the event
public event RoutedEventHandler foo
{
add => AddHandler(fooEvent, value);
remove => RemoveHandler(fooEvent, value);
}
}
XAML。
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication3"
Title="MainWindow" Height="350" Width="525">
<Window.Triggers>
<EventTrigger RoutedEvent="local:MainWindow.foo" />
</Window.Triggers>
</Window>
编辑: 显示相同的解析器错误,直到重新构建项目为止。
<Window.Triggers>
<EventTrigger RoutedEvent="{x:Static local:MainWindow.foo}" />
</Window.Triggers>
我遇到了同样的问题,但你的所有解决方案都不适合我。 上面的这段代码确实解决了我的问题。
我遇到了同样的问题,但重建对我不起作用,直到我重新启动我的工作室。关闭它并重新打开该项目,效果很好。