擷取路由事件的源Source和OriginalSource,originalsource

來源:互聯網
上載者:User

擷取路由事件的源Source和OriginalSource,originalsource
路由事件的訊息包含在RoutedEventArgs執行個體中,該執行個體有兩個屬性Source和OriginalSource,都是表示路由事件傳遞的起點,即事件訊息的源頭,只不過Source表示的是LogicalTree上的訊息源頭,而OriginalSource表示的是VisualTree上的源頭。

主要代碼如下:

public MainWindow(){    InitializeComponent();    this.AddHandler(Button.ClickEvent, new RoutedEventHandler(this.ButtonClicked));}void ButtonClicked(object sender, RoutedEventArgs e){    string SourceString = string.Format("LogicalTree start point: {0}, type is {1}",        (e.Source as FrameworkElement).Name, e.Source.GetType().Name);    string OriginalSourceString = string.Format("VisualTree start point: {0}, type is {1}",        (e.OriginalSource as FrameworkElement).Name, e.OriginalSource.GetType().Name);    MessageBox.Show(OriginalSourceString + "\r\n" + SourceString);}



WPF裡面下列三種表達方式的不同?

其實應該使用 sender as Button;

顯然 btn_Click(...) 是一個函數, 它可以被調用. 例如, 在其他函數中調用:
private void InvokeProxy()
{
btn_Click(null, null);
btn_Click(123, null); // sender 是 object.
...
...
}

顯然, btn_Click 被調用時 兩個參數都是 null 的.
所以

Button btn = sender as Button;
if(btn==null)
{
// ... 不是由 Button 調用的.
}

因此區別在於:
Button btn = (Button)sender; // 當 sender 無法轉換為 Button 時出出現 Exception.

Button btn = sender as Button; // 當無法轉換時, btn 是 null, 無異常.

Button btn = e.Source as Button; // 同上差不差, 只是企圖將 e 的 Source 轉換為 Button, 不成功時 btn 為 null. 應該還需要判斷 e==null.

Button btn = e.OriginalSource as Button;
這個你應該看看 RoutedEvent 的機制(路由事件機制). 製造事件 "元兇" 可能不是 e.Source, 可能是 e.OriginalSource, 在可以 Bubble 的路由裡, 只要 e.Handled 未置為 True, 就可能繼續沸升.
 
我要搶第一

你已經不行了,只搶道了第三
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.