Search code examples
wpfdatatemplatemenuitem

WPF - MenuItem Icon using data templates


I have a menuitem with an itemsource set to a collection of differing types. For each type, I have defined a datatemplate within the resource section.

How do I go about setting the menuItems Icon depending on the datatype?

Edit : Whilst the ideas suggested by Brian would have worked, I didn't want the viewmodel to be specifying the image resource itself, but rather a tag for the View to switch on, and so went for the following.

<Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
            <Setter Property="Command" Value="{Binding Process}"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Usage}" Value="UsageA">
                    <Setter Property="Icon" Value="{StaticResource imgA}"/>
                </DataTrigger>

                <DataTrigger Binding="{Binding Usage}" Value="UsageB">
                    <Setter Property="Icon" Value="{StaticResource imgB}"/>
                </DataTrigger>

                <DataTrigger Binding="{Binding Usage}" Value="UsageC">
                    <Setter Property="Icon" Value="{StaticResource imgC}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>

Solution

  • You have to create a Style for the MenuItem's ItemContainerStyle. In the style, you can bind the Icon for the MenuItem to a property on your object. It would look something like this:

    <Style x:Key="MyMenuItemStyle" TargetType="MenuItem">
       <Setter Property="Header" Value="{Binding MenuName}"/>
       <Setter Property="Command" Value="{Binding MenuCommand}"/>
       <Setter Property="Icon" Value="{Binding MenuIcon}" />
     </Style>
    

    You could also do this in the DataTemplate by using a Horizontal StackPanel and just displaying both an Image and the Text for the menu, but that won't really be utilizing the Icon property of the MenuItem, that will just be adding an image to the Content of the MenuItem.

    The ItemContainerStyle defines the container for the MenuItem, and allows you to assign the Icon property of the MenuItem.