[WPF] 如何取得觸發快顯功能表(右鍵選單)的來源控制項呢?

在WPF中,右鍵選單的功能是利用ContextMenu來達成,如果是用程式碼的方式來幫控制項添加右鍵選單,會大概是下面的方式

                Image image = new Image();
                MenuItem propertyMenu = new MenuItem();
                propertyMenu.Header = "Propertys...";
                propertyMenu.Click += ImagePropertyMenu_Click;
                image.ContextMenu = new ContextMenu();
                image.ContextMenu.Items.Add(propertyMenu);

在上面的程式碼中,可以看到在新增右鍵選單的同時,也將Click事件掛載上去了;事件掛載的程式碼會大約是這樣

        static void ImagePropertyMenu_Click(object senderRoutedEventArgs e)
        {
            WinPropertys propertyWindow = new WinPropertys();
            
            propertyWindow.ShowDialog();
        }

在一般的使用情形下,這沒有任何問題,如果只是單純的要呼叫顯示其他的window;但是如果是要做一個像是屬性設定的功能,例如以這個例子來說,我的來源控制項是一個Image,呼叫出來的新視窗中,我希望可以顯示出這個Image的寬度、高度、位置等資訊,那麼應該怎麼處理?在MenuItem的Click事件中,你可以看到不論是e.Source或是Sender,觸發這個事件的都是MenuItem,所以不能夠直接抓到觸發的來源控制項,這個時候就要利用下面的方式來抓取了
        static void ImagePropertyMenu_Click(object senderRoutedEventArgs e)
        {
            WinPropertys propertyWindow = new WinPropertys();
            propertyWindow.mapedElement =
                (FrameworkElement)(e.Source as MenuItem).Parent.GetValue(ContextMenu.PlacementTargetProperty);
            propertyWindow.ShowDialog();
        }
        #endregion

主要就是利用ContextMenu的PlacementTargetProperty屬性,詳細的說明可以參考MSDN的說明,小技巧給大家參考看看了

留言

這個網誌中的熱門文章

開啟cshtml檔案時,出現『並未將物件參考設定為物件執行個體』的錯誤訊息

無法設定中斷點 尚未載入符號檔

DataGridView欄位計算總合