2011-02-14 15 views
1

仍然爬上陡峭的WPF山,並且感到痛苦。當從UserControl引發MouseButtonEvent時,MainWindow無法訪問MouseButtonEventArgs

我已經定義了一個用戶控件,我的主窗口需要檢索MouseButtonEventArgs從用戶控件裏的控件來(例如像鼠標e.GetPosition)

在後面的用戶控件的代碼,我也做了註冊記憶我舉起冒泡事件。

public static readonly RoutedEvent MyButtonDownEvent = EventManager.RegisterRoutedEvent("MyMouseButtonDown", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl)); 
    public event RoutedEventHandler MyButtonDown { 
     add { AddHandler(MyButtonDownEvent, value); } 
     remove { RemoveHandler(MyButtonDownEvent, value); } 
    } 
    private void MyMouseButtonDownHandler(object sender, MouseButtonEventArgs e) { 
     RaiseEvent(new RoutedEventArgs(MyButtonDownEvent)); 
    } 

現在在我的主窗口,我宣佈類似這樣的用戶控件:

<local:MyUserControl MouseDown="MyUserControl_MouseDown"/> 

背後

private void MyUserControl_MouseDown(object sender, RoutedEventArgs e) 

這個代碼,我收到來自用戶控件的事件,但ARG遊戲RoutedEventArgs (這是正常的),但我沒有訪問MouseButtonEventArgs,我需要得到鼠標e.GetPosition。

在這種情況下,你會建議什麼優雅的解決方案?

回答

0

我想,我終於拿到了它(至少我希望如此):

如果我在寫代碼背後:

 public event EventHandler<MouseButtonEventArgs> MyRightButtonDownHandler; 
    public void MyRightButtonDown(object sender, MouseButtonEventArgs e) { 
     MyRightButtonDownHandler(sender, e); 
    } 

然後在消費者(主窗口)XAML:

<local:GlobalDb x:Name="globalDb" MyRightButtonDownHandler="globalDb_MyRightButtonDownHandler"/> 

而且在後面的消費者代碼:

private void globalDb_MyRightButtonDownHandler(object sender, MouseButtonEventArgs e) { 
     Console.WriteLine("x= " + e.GetPosition(null).X + " y= " + e.GetPosition(null).Y); 
    } 

請告訴我,如果你有一個更好的解決方案(在設計策略 - 規則制定在哪裏工作 - 我的應用程序的所有事件處理必須出現在XAML中)。再次

感謝您的幫助,

+0

找到了解決方案 –

+0

是的,這就是我的意思,它比使用路由事件更簡單,當然有時您的事件需要路由 –

1

爲什麼要定義自己的MouseDown事件,而UserControl已經有一個正常的MouseDown事件?

無論如何,如果你定義一個事件來使用RoutedEventHandler,你最終會陷入RoutedEventHandler並不奇怪。你宣稱它是這樣的:

public static readonly RoutedEvent MyButtonDownEvent = EventManager.RegisterRoutedEvent("MyMouseButtonDown", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl)); 

通知,它說typeof(RoutedEventHandler)位?

如果我沒有記錯你的代碼看起來應該是這樣,而不是:如何傳播現有的MouseDown事件自定義事件

public static readonly RoutedEvent MyButtonDownEvent = 
     EventManager.RegisterRoutedEvent 
     ("MyButtonDown", 
     RoutingStrategy.Bubble, 
     typeof(MouseButtonEventHandler), 
     typeof(MyUserControl)); 

    public event MouseButtonEventHandler MyButtonDown 
    { 
     add { AddHandler(MyButtonDownEvent, value); } 
     remove { RemoveHandler(MyButtonDownEvent, value); } 
    } 

例子:

InitializeComponent(); 
this.MouseDown += (s, e) => { 
    RaiseEvent(new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, e.ChangedButton) 
        { 
         RoutedEvent = MyButtonDownEvent 
        }); 
}; 
+0

HB您好,謝謝您的努力 –

+0

HB您好,感謝您的幫助。回覆你的評論「爲什麼你定義了自己的MouseDown事件,而UserControl已經有一個正常的MouseDown事件?」。我沒有找到方法來在MainWindow中僅使用XAML來訂閱來自UserControl的事件。我也測試了你的代碼,並注意到XAML認爲類型不匹配。任何想法 ? –

+0

不,我試圖修復它一段時間,但沒有解決。如果你不介意不把它註冊爲RoutedEvent,那麼應該沒有問題(你需要擺脫setter和getter的事件) –