2016-02-25 44 views
0

我有一個WPF MainWindow和我自己的RoutedEvent,當按下Enter鍵時會引發它。爲什麼在我的xaml中沒有處理自定義routedevent

namespace ZK16 
{ 
public partial class MainWindow : Window 
{ 

    public static readonly RoutedEvent CustomEvent = EventManager.RegisterRoutedEvent(
     "Custom", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MainWindow)); 

    public event RoutedEventHandler Custom 
    { 
     add { AddHandler(CustomEvent, value); } 
     remove { RemoveHandler(CustomEvent, value); } 
    } 

    void RaiseCustomEvent() 
    { 
     Debug.WriteLine("RaiseCustomEvent"); 
     RoutedEventArgs newEventArgs = new RoutedEventArgs(MainWindow.CustomEvent); 
     RaiseEvent(newEventArgs); 
    } 

    public MainWindow() 
    { 
     InitializeComponent(); 
     this.AddHandler(MainWindow.CustomEvent, new RoutedEventHandler(MyCustomHandler)); 
    } 

    private void MyCustomHandler(object sender, RoutedEventArgs e) 
    { 
     Debug.WriteLine("In Eventhandler..."); 
    } 

    private void Window_PreviewKeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.Enter) 
      RaiseCustomEvent(); 
    } 

在XAML我添加一個Label與一個EventTrigger,

<Window x:Class="ZK16.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:ZK16" 
    Title="MainWindow" 
    PreviewKeyDown="Window_PreviewKeyDown" 
    > 
<Grid> 
    <Label Content="Hello World"> 
     <Label.Triggers> 
      <EventTrigger RoutedEvent="local:MainWindow.Custom"> 
       <BeginStoryboard> 
        <Storyboard Duration="00:00:1"> 
         <DoubleAnimation From="6" To="25" Storyboard.TargetProperty="FontSize"/> 
        </Storyboard> 
       </BeginStoryboard> 
      </EventTrigger> 
     </Label.Triggers> 
    </Label> 
</Grid> 
</Window> 

但提高自定義事件時, 的EventTrigger不會觸發我的事件,但如果觸發例如

EventTrigger RoutedEvent="Loaded" 

有人可以告訴我,怎麼了?

回答

2

我認爲對路由事件是什麼有一個微小的理解。

MSDN article狀態如下:

冒泡:在事件源上的事件處理程序調用。路由事件然後路線連續父元素直至到達元件樹根...

隧道:首先,在所述元件樹根事件處理程序被調用。路由事件隨後穿過連續的子元素沿線,朝着那就是路由事件源(即提高了路由事件的元素)的節點處的路由...

你的情況,你有冒泡事件。你在MainWindow(來源)中提高它,所以它將從該元素向上開始。沒有什麼是MainWindow以上,所以它停在那裏。

如果您將事件更改爲隧道事件,則會發生這種情況。你從MainWindow(來源)提高它,所以事件開始從父母傳播到源,再次,沒有什麼是MainWindow以上,結果相同。

現在,如果你在你的XAML如下:

<Label x:Name="MyLabel" Content="Hello World"> 

這在你的代碼:

MyLabel.RaiseEvent(newEventArgs); 

的路線將是一個冒泡事件的情況下,下面:

Label(source) - >Grid - >MainWindow

而在隧道事件的情況:

MainWindow - >Grid - >Label(源)

此人有同樣的問題here

+0

很好的回答!非常感謝 –

相關問題