Routing Strategies:
- Direct
- Bubbling
- Tunneling
WHy use them?
- Any UIElement can be a listener
- Common handlers
- Visual Tree Communication
- Event Setter and Event Trigger
Routed Event Example:
<Window x:Class="CustomControlDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Width="350" Height="220" ButtonBase.Click="Window_Click"> //listen to the RoutedEvent:ButtonBase.Click and handle RoutedEvent using Window_Click <Grid> <StackPanel Margin="20" ButtonBase.Click="StackPanel_Click"> //listen to the RoutedEvent:ButtonBase.Click and handle RoutedEvent using StackPanel_Click <Border BorderBrush="Red" BorderThickness="5"> <TextBlock Margin="5" FontSize="18" Text="This is a TextBlock" /> </Border> <Button Margin="10" Click="Button_Click" //handle the Button.Click event using Button_Click handler Content="Click me" /> </StackPanel> </Grid> </Window>
namespace CustomControlDemo { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { //Button层的event handler,由于ButtonBase.Click是routedEvent所以可以向上bubble } private void StackPanel_Click(object sender, RoutedEventArgs e) {
e.Handled = true; //StackPanel层的event handler,不继续向上传
e.Handled = false; //StackPanel层的event handler,继续向上传 } private void Window_Click(object sender, RoutedEventArgs e) { //Window层的event handler,已传到最上层 } } }
我们也可以不在xaml写handler,直接用后台控制
namespace CustomControlDemo { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); AddHandler(Button.ClickEvent, new RoutedEventHandler(Window_Click), true); //即使e.Handled = true;我们也要routedevent继续传到window层 } private void Button_Click(object sender, RoutedEventArgs e) { //Button层的event handler,由于ButtonBase.Click是routedEvent所以可以向上bubble } private void StackPanel_Click(object sender, RoutedEventArgs e) { e.Handled = true; } private void Window_Click(object sender, RoutedEventArgs e) { } } }
Custom Routed Events
- register your event
- choose your routing strategy
- provide add and remove CLR wrapper
- Raise your event