Csaba Czine

Csaba Czine

  • NA
  • 11
  • 40.9k

Binding an Icon of MenuItem in WPF

May 12 2015 11:57 AM
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)