在XAML代码中为节点树安装事件监听器

通过以下的演示样例代码,能够发现,我们能为随意的节点指定要监听的路由事件,而这个路由事件本身和这个元素可能根本就没有关系。
<Window x:Class="Demo002.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Demo002"
        Title="MainWindow" Height="350" Width="525">
    <Grid x:Name="Grid1" local:TimeButton.ReportTime="ReportTimeHandler">
        <Grid x:Name="Grid2" local:TimeButton.ReportTime="ReportTimeHandler">
            <Grid x:Name="Grid3" local:TimeButton.ReportTime="ReportTimeHandler">
                <StackPanel x:Name="StackPanel1" local:TimeButton.ReportTime="ReportTimeHandler">
                    <ListBox x:Name="ListBox1" />
                    <local:TimeButton x:Name="TimeButton1" Width="80" Height="80" 
                                      Content="Report Time"
                                      local:TimeButton.ReportTime="ReportTimeHandler"/>
                </StackPanel>
            </Grid>
        </Grid>
    </Grid>
</Window>

当ReportTime的路由事件被触发之后,该事件会沿着树进行传递,假设到了某个节点我们已经把该事件处理了,而且无需继续往上传递,则能够通过其參数e.Handled=true来控制其无需继续传递下去了。例如以下代码所看到的:
private void ReportTimeHandler(object sender, ReportTimeEventArgs e)
{
    FrameworkElement element = sender as FrameworkElement;
    string content = string.Format("{0}到达{1}", e.ClickTime.ToLongTimeString(), element.Name);
    this.ListBox1.Items.Add(content);


    if (element == this.Grid2) { e.Handled = true; }
}

依照上面的代码,当路由事件传递给Grid2的时候,就被标记为已经处理了,这样路由事件就不会再传递给Grid1了。
原文地址:https://www.cnblogs.com/bhlsheji/p/4217022.html