Alexus
Alexus

Reputation: 296

Menu item icon added programmatically is not displayed

I have a display menu item icon issue when trying to add a checked image programmatically:

private void ObjectsCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    ContextMenu cm = new ContextMenu();

    MenuItem mDiag = new MenuItem();
    mDiag.Icon = new System.Windows.Controls.Image
    {
        Source = (new BitmapImage(new Uri("assets/checked-32-context.png", UriKind.Relative)))
    };
    mDiag.Header = Application.Current.Resources["DiagScreenMenuText"].ToString();

    cm.Items.Add(mDiag);
    cm.PlacementTarget = sender as Button;
    cm.IsOpen = true;
}

The checked-32-context.png image is used only here, but not displayed :

enter image description here

Upvotes: 1

Views: 1227

Answers (1)

Clemens
Clemens

Reputation: 128181

In contrast to XAML, it is necessary to specify the full Resource File Pack URI in code behind:

mDiag.Icon = new System.Windows.Controls.Image
{
    Source = new BitmapImage(new Uri(
        "pack://application:,,,/assets/checked-32-context.png"))
};

Note also that this is not a relative URI.

Upvotes: 3

Related Questions