Rather than use an event generated by an input device, I want to use a custom event that will be raised programatically in the code-behind as an EventTrigger in my xaml.
This should be laughably easy but I can't find an example anywhere.
Here's what I've come up with from studying WPF4 Unleashed Chapter 6, Routed Event Implementation, EventTrigger.RoutedEvent Property, Custom RoutedEvent as EventTrigger, and many others:
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:
P.S. Please be gentle, I am relatively new to WPF.
Okuma Scott,
Have you tried to build (rebuild) the project. WPF requires you to build the project in order for the project changes to be visible to the XAML parser. Using the code below builds just fine.
Code
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>
Edit: The same parser error was displayed until the project was re-built.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With