• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1286
  • Last Modified:

Add an icon to WPF contextmenu from resources in code behind

How can I add an icon to a WPF contextmenu from the application resources in code behind?

The resource can be either an icon or png, whichever is easiest.
1 Solution
You may approach this by adding a property in your CodeBehind or ViewModel.
I recommend using a ViewModel (using the MVVM pattern) because it may (in my opinion) reduce code and improve scalability.
But you can also make this in your VodeBehind.

First of all, you will need to implement the "INotifyPropertyChanged".

Then add some properties:
public String MenuItemHeader
    get { return (String)GetValue(MenuItemHeaderProperty); }
        SetValue(MenuItemHeaderProperty, value);

public String MenuItemIcon
    get { return (String)GetValue(MenuItemIconProperty); }
        SetValue(MenuItemIconProperty, value);

Open in new window

And some dependency properties for the properties:
public static readonly DependencyProperty MenuItemHeaderProperty = DependencyProperty.Register("MenuItemHeader", typeof(String), typeof(MyClassName), new PropertyMetadata(null));
public static readonly DependencyProperty MenuItemIconProperty = DependencyProperty.Register("MenuItemIcon", typeof(String), typeof(MyClassName), new PropertyMetadata(null));

Open in new window

The ContextMenu on your control may look like this:
        <MenuItem Header="{Binding MenuItemHeader}"
                  Icon="{Binding MenuItemImage}"/>

Open in new window

Then you can set this code to set the ContextMenu text and icon:
MenuItemHeader = "This is the contextmenu text";
MenuItemIcon = "/MyWpfApplication;component/Images/save.png";

Open in new window

But there are many ways.
You amy also place "x:Name="SomeControl"" on the controls and add it "the old way" :-)
That's up to you to decide.

Hope it helps :-)
CatsSolutionsAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now