在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了。
發佈了359 篇原創文章 · 獲贊 211 · 訪問量 95萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章