参考JusterZhu视频和文档,ppt文档基本全抄
一、RoutedEvent
路由事件分为两种(Preview )隧道事件和冒泡事件,当控件之间的层级嵌套越来越多时事件的触发和传递就变的比之前复杂。路由事件的出现就是为了解决此类问题。路由事件具有传播性。
<Window
x:Class="Chapter7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Chapter7"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<StackPanel>
<Grid
Width="150"
Height="60"
Background="Red"
MouseDown="Grid_MouseDown">
<Button
Width="100"
Height="30"
Click="Button_Click_1"
Content="PointToPoint" />
</Grid>
<Grid
x:Name="grid1"
Width="150"
Margin="5"
Background="Red">
<StackPanel
x:Name="stackPanel1"
Margin="10"
Background="Yellow">
<Button
x:Name="button1"
Width="100"
Height="50"
Margin="5"
Content="RoutedEvent" />
</StackPanel>
</Grid>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Chapter7
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//冒泡路由,由事件源向上传递一直到根元素
//grid1.AddHandler(Button.ClickEvent, new RoutedEventHandler(Grid_Click));
//stackPanel1.AddHandler(Button.ClickEvent, new RoutedEventHandler(StackPanel_Click));
//button1.AddHandler(Button.ClickEvent, new RoutedEventHandler(Button_Click));
//隧道路由,从元素树的根部调用事件处理程序并依次向下深入直到事件源
grid1.AddHandler(Button.PreviewMouseLeftButtonDownEvent, new RoutedEventHandler(Grid_Click));
stackPanel1.AddHandler(Button.PreviewMouseLeftButtonDownEvent, new RoutedEventHandler(StackPanel_Click));
button1.AddHandler(Button.PreviewMouseLeftButtonDownEvent, new RoutedEventHandler(Button_Click));
}
private void Grid_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Grid.Click");
}
private void StackPanel_Click(object sender, RoutedEventArgs e)
{
e.Handled = true;
MessageBox.Show("StackPanel.Click");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Button.Click");
}
//Point to Point
private void Button_Click_1(object sender, RoutedEventArgs e)
{
MessageBox.Show("Button.Click");
}
//Point to Point
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("Grid.MouseDown");
}
}
}