2017-05-26 51 views
0

我正在使用C#和WPF在Visual Studio中處理項目。我有一個Datagrid,我想以編程方式創建/定製其上下文菜單項。以編程方式自定義C#中的上下文菜單項WPF

這裏是如何我目前正在創建菜單項:

 MenuItem Enable; 
     Enable = new MenuItem(); 

     dgdProcessList.ContextMenu.Items.Add(Enable); 
     Enable.Header = "Enable"; 

現在我希望把該菜單項的圖標,但我有麻煩搞清楚我怎麼能點圖標的項目中的現有文件。它目前位於我的項目的Resources \ Icons \ SampleIcon.ico中。我如何在這裏適當地引用它:

Enable.Icon = ???; 

另外,我想這個菜單項點擊時觸發一個函數。如何使用以下代碼執行此操作:

Enable.Click = ???; 

道歉,如果這很簡單。我研究了與這個問題有關的各種話題,但無法弄清楚。

+0

下面是例子如何設置圖標https://stackoverflow.com/a/74671/6064728 –

+0

這裏是例如,對於點擊事件處理程序https://stackoverflow.com/questions/4663372/how-to-add-event-handler-programmatically-in-wpf-like-one-can-do-in-winform –

+0

你有沒有至少試圖尋找答案之前問問題? –

回答

0

你需要的是這樣的:

var imgEdit = (BitmapImage) Application.Current.FindResource("Edit"); 
var mnu = new MenuItem {Header = title}; 
if (imgEdit != null) mnu.Icon = new Image {Height = 16, Width = 16, Source = imgEdit}; 

只要你的圖標是在被你的App.xaml中引用的資源字典你要善於即:

在您的ResourceDictionary將這個:

<BitmapImage UriSource="/MyApp;component/Images/Light/edit.png" x:Key="Edit" PresentationOptions:Freeze="True" /> 

而在你App.xaml中有這樣的:

<ResourceDictionary Source="Resources/ImageStyles.xaml" /> 

,並啓用單擊做一些事情,像這樣:

mnu.Click += (o, e) => callback();