<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了。