Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why only the last menu item has icon?

Tags:

c#

wpf

In WPF, I'm programmatically adding a context menu to a control.

    var contextMenu = new ContextMenu();
    contextMenu.Items.Add(new MenuItem { Header = "Copy All", Icon  = FindResource("CopyImage") });
    contextMenu.Items.Add(new MenuItem { Header = "Copy All with Headers", Icon = FindResource("CopyImage") });
    contextMenu.Items.Add(new MenuItem { Header = "Copy Selected", Icon = FindResource("CopyImage") });
    contextMenu.Items.Add(new MenuItem { Header = "Copy Selected with Headers", Icon = FindResource("CopyImage") });

CopyImage is defined in my application resource.

<Image x:Key="CopyImage" Source="../Images/copy.png"/>

At runtime, only the last menu item shows the icon. The other three menu items do not.

enter image description here

Does anyone have an explanation for this behavior?

like image 312
Igor Pashchuk Avatar asked Aug 17 '15 16:08

Igor Pashchuk


2 Answers

Take a look at this article.

It explains that an Image can only be used in one place at a time. That would explain why it only ended up on the most recent assignment you made in code. Instead, define a BitmapImage and then create a new image using the BitmapImage as the source for each menu item.

From other article:

To do this, create a BitmapSource as a resource somewhere:

<BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" />

Then, in your code, use something like:

<Image Source="{StaticResource MyImageSource}" />
like image 166
Nathan A Avatar answered Nov 01 '22 02:11

Nathan A


Each UI Element can only be placed in one location in the visual tree. You can't use the same Image control on multiple MenuItem's. You need to create separate Image controls for each MenuItem. Otherwise each time you assign it to a new MenuItem, you are just moving it from one to the next.

<Image x:Key="CopyImage1" Source="../Images/copy.png"/>
<Image x:Key="CopyImage2" Source="../Images/copy.png"/>
<Image x:Key="CopyImage3" Source="../Images/copy.png"/>
<Image x:Key="CopyImage4" Source="../Images/copy.png"/>

var contextMenu = new ContextMenu();
    contextMenu.Items.Add(new MenuItem { Header = "Copy All", Icon  = FindResource("CopyImage1") });
    contextMenu.Items.Add(new MenuItem { Header = "Copy All with Headers", Icon = FindResource("CopyImage2") });
    contextMenu.Items.Add(new MenuItem { Header = "Copy Selected", Icon = FindResource("CopyImage3") });
    contextMenu.Items.Add(new MenuItem { Header = "Copy Selected with Headers", Icon = FindResource("CopyImage4") });
like image 25
Glen Thomas Avatar answered Nov 01 '22 04:11

Glen Thomas