0

I'm working on a project in Visual Studio using C# and WPF. I have a Datagrid and I would like to Programatically create/customize its context menu items.

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. 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.

E. Box
  • 23
  • 1
  • 5

1 Answers1

0

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:

Put this in your ResourceDictionary:

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

And have this in your App.xaml:

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

And to enable the Click do something like so:

mnu.Click += (o, e) => callback();
Kelly
  • 6,992
  • 12
  • 59
  • 76