Oku*_*ott 2 c# wpf xaml code-behind routed-events
我想使用一个自定义事件,而不是使用输入设备生成的事件,该事件将在我的xaml中作为EventTrigger在代码隐藏中以编程方式引发.
这应该是可笑的,但我无法在任何地方找到一个例子.
以下是我从学习WPF4 Unleashed第6章,路由事件实现,EventTrigger.RoutedEvent属性,自定义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); }
}
}
}
Run Code Online (Sandbox Code Playgroud)
MainWindow.xaml:

PS请温柔,我对WPF比较新.
Okuma Scott,
您是否尝试构建(重建)项目.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); }
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
编辑:显示相同的解析器错误,直到重新构建项目.
| 归档时间: |
|
| 查看次数: |
4861 次 |
| 最近记录: |