简体   繁体   English

以编程方式自定义C#WPF中的上下文菜单项

[英]Programatically customize context menu item in C# WPF

I'm working on a project in Visual Studio using C# and WPF. 我正在使用C#和WPF在Visual Studio中进行项目。 I have a Datagrid and I would like to Programatically create/customize its context menu items. 我有一个Datagrid,我想以编程方式创建/自定义其上下文菜单项。

Here is how I'm currently creating the menu item: 这是我当前创建菜单项的方式:

        MenuItem Enable;
        Enable = new MenuItem();

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

Now I want to place a icon for that menu item, however I am having trouble figuring out how can I point the icon to an existing file in the project. 现在,我想为该菜单项放置一个图标,但是我在弄清楚如何将图标指向项目中的现有文件时遇到了麻烦。 It's currently located in Resources\\Icons\\SampleIcon.ico of my project. 当前位于我项目的Resources \\ Icons \\ SampleIcon.ico中。 How do I properly reference it here: 我如何在这里正确引用它:

Enable.Icon = ???;

Also, I would like this menu item to trigger a function when clicked. 另外,我希望此菜单项在单击时触发功能。 How do I do this with the following code: 如何使用以下代码执行此操作:

Enable.Click = ???;

Apologies if this is something simple. 抱歉,这很简单。 I looked at various topics relating to this issue, but wasn't able to figure it out. 我查看了与此问题相关的各种主题,但无法弄清楚。

What you need is this: 您需要的是:

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};

As long as your icon is in a ResourceDictionary that is referenced in your App.xaml you should be good ie: 只要您的图标位于App.xaml中引用的ResourceDictionary中,您就应该是不错的,即:

Put this in your ResourceDictionary: 将其放在您的ResourceDictionary中:

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

And have this in your App.xaml: 并将其放在您的App.xaml中:

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

And to enable the Click do something like so: 要启用“点击”,请执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM