3
Answers

Binding an Icon of MenuItem in WPF

Csaba Czine

Csaba Czine

9y
994
1
I had to create a dynamic list of submenuitems in WPF. I had to bind the Icon of the MenuItem to the DataSource as well. I found, that the binding works in some cases odd. Look at my code:
<Style x:Key="badMenuItem_ItemContainerStyle" TargetType="MenuItem">
    <Setter Property="Header" Value="{Binding Header}" />
    <Setter Property="Icon">
        <Setter.Value>
            <Image Width="20" Height="20" Source="{Binding ImageSource}" />
        </Setter.Value>
    </Setter>
</Style>

<
Image x:Key="image" Source="{Binding ImageSource}" Width="20" Height="20" x:Shared="False"/>
<Style x:Key="goodMenuItem_ItemContainerStyle" TargetType="MenuItem">
    <Setter Property="Header" Value="{Binding Header}" />
    <Setter Property="Icon" Value="{StaticResource image}" />
</Style>
 
 The I first used the badMenuItem_ItemContainerStyle as the ItemContainerStyle of my MenuItem, to which I added the child MenuItems through a binding. It works the following way: The Image as Icon appears correctly on the UI, but only in the last child MenuItem. If I define a Converter for the binding, the converter will be called for each MenuItem. The binding seems to work, but the images do not appear. The goodMenuItem_ItemContainerStyle works correctly. Can someone explain me what is wrong with the badMenuItem_ItemContainerStyle?
Answers (3)
0
Csaba Czine

Csaba Czine

NA 11 23.5k 9y
An important attribute for the image resource is cut off on the screen: x:Shared="False"
0
Csaba Czine

Csaba Czine

NA 11 23.5k 9y
The same image source pathes are used in both the good and the bad versions. The MenuItems are bound to the same collection, and the same image source pathes are returned from the DataContext. The cause has to be something different.
0
ramya bharath

ramya bharath

NA 922 0 9y
Check the image source path it should be a relative path pointing to the file