So, I have a Context Menu And a MenuItem in it, which is broken down into a list of names:
<ContextMenu> <MenuItem Header="Set As Default For" ItemsSource="{Binding Source={StaticResource Names}}"> <MenuItem.ItemContainerStyle> <Style TargetType="MenuItem"> <Setter Property="Header" Value={Binding Name}/> <Setter Property="Command" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MenuItem}, Path=DataContext.DoSomething}" /> <Setter Property="CommandParameter" Value="{Binding }" /> </Style> </MenuItem.ItemContainerStyle> </MenuItem> </ContextMenu>
Now the above code works with the file and displays a list of my names. Now I would like to add an icon next to each name using the package URI. So from this question . I see that the best way to do this is to create a Header template, so I tried this first as a question
<ContextMenu> <MenuItem Header="Set As Default For" ItemsSource="{Binding Source={StaticResource Names}}"> <MenuItem.ItemContainerStyle> <Style TargetType="MenuItem"> <Setter Property="Header"> <Setter.Value> <StackPanel> <Image Width="20" Height="20" Source="/MyProj;component/Resources/MyImg.png" /> <ContentPresenter Content="{Binding Name}" /> </StackPanel> </Setter.Value> </Setter> <Setter Property="Command" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MenuItem}, Path=DataContext.DoSomething}" /> <Setter Property="CommandParameter" Value="{Binding }" /> </Style> </MenuItem.ItemContainerStyle> </MenuItem> </ContextMenu>
but this gave me an error:
The specified element is already a logical child of another element. Disable it first.
So, after some research, I tried:
<ContextMenu> <MenuItem Header="Set As Default For" ItemsSource="{Binding Source={StaticResource Names}}"> <MenuItem.ItemContainerStyle> <Style TargetType="MenuItem"> <Setter Property="Header"> <Setter.Value> <ControlTemplate> <StackPanel> <Image Width="20" Height="20" Source="/MyProj;component/Resources/MyImg.png" /> <ContentPresenter Content="{Binding Name}" /> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Command" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MenuItem}, Path=DataContext.DoSomething}" /> <Setter Property="CommandParameter" Value="{Binding }" /> </Style> </MenuItem.ItemContainerStyle> </MenuItem> </ContextMenu>
But now all my names are ControlTemplate and the icon is not showing ...
How to add an icon to a context menu menu item through ItemContainerStyle?
EDIT
I tried:
<Setter Property="Header" Value="{Binding Name}"/> <Setter Property="Icon"> <Setter.Value> <Image Width="20" Height="20" Source="/MyProj;component/Resources/MyImg.png" /> </Setter.Value> </Setter>
And I get icon rendering, but only for the last item in my menu?