1. 程式人生 > >WPF事件中的冒泡路由事件

WPF事件中的冒泡路由事件

<Window x:Class="冒泡路由事件.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:冒泡路由事件"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="329" MouseUp="SomethingClicked">
    <Grid Margin="3" MouseUp="SomethingClicked">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <Label Margin="5" Grid.Row="0" HorizontalAlignment="Left" Background="AliceBlue" 
               BorderBrush="Black" BorderThickness="1" MouseUp="SomethingClicked">
            <StackPanel MouseUp="SomethingClicked">
                <TextBlock MouseUp="SomethingClicked">Image and Text Lable</TextBlock>
                <TextBlock MouseUp="SomethingClicked">Courtesy of the Stackpanel</TextBlock>
            </StackPanel>
        </Label>
        <ListBox Grid.Row="1" MouseUp="SomethingClicked" Name="listbox" Margin="5"></ListBox>
        <CheckBox Grid.Row="2" Margin="5" Name="checkbox">Hand first event</CheckBox>
        <Button Grid.Row="3" Margin="5" Padding="3" HorizontalAlignment="Right"
                Name="btn" Click="btn_Click">Clear list</Button>
        </Grid>
</Window>

namespace 冒泡路由事件
{
    /// <summary>
    /// MainWindow.xaml 的互動邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        protected int eventcounter = 0;
        public MainWindow()
        {
            InitializeComponent();
        }
        
        private void SomethingClicked(object sender, MouseButtonEventArgs e)
        {
            eventcounter++;                                    //計數加一
            string messages = "#" + eventcounter + ":\n" + "Sender:" + sender + "\n" + "source:" + e.Source + "\n" + "original:" + e.OriginalSource + "\n";
            listbox.Items.Add(messages);
            e.Handled = (Boolean)checkbox.IsChecked;                        //選中就handled住事件,不路由

        }

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            listbox.Items.Clear();
            eventcounter = 0;
        }
    }
}

為控制元件新增統一的滑鼠擡起事件SomethingClicked,在listbox中展示出事件發生的物件,源物件