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.
Does anyone have an explanation for this behavior?
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}" />
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") });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With