I have the need to replace the Icon in a MenuItem with a Rectangle. Currently I have this:
<TextBox.ContextMenu>
<ContextMenu Focusable="False" ItemsSource="{Binding Categories}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding Name}"/>
<Setter Property="Focusable" Value="False"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</TextBox.ContextMenu>
Which works fine:

But I can't figure out how to edit the MenuItem.Icon and replace it with a rectangle.
I've tried using a DataTemplate:
<TextBox.ContextMenu>
<ContextMenu Focusable="False" ItemsSource="{Binding Categories}">
<ContextMenu.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<Rectangle Width="20" Height="20" Fill="{Binding CategoryColor}"/>
<Label Content="{Binding Name}"/>
</StackPanel>
</DataTemplate>
<ContextMenu.ItemTemplate>
</ContextMenu>
</TextBox.ContextMenu>
And while this looks okay it would be nicer to get the Rectangle into the Icon area - or remove the icon area altogether. I also have to think about binding a Command to the MenuItem, if that makes a difference to the approach.

POSSIBLE SOLUTION: I've tried:
<TextBox.ContextMenu>
<ContextMenu Focusable="False" ItemsSource="{Binding Categories}">
<ContextMenu.Resources>
<Rectangle x:Key="myRectangle" x:Shared="False" Width="20" Height="20" Fill="{Binding CategoryColor}"/>
</ContextMenu.Resources>
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding Name}"/>
<Setter Property="Focusable" Value="False"/>
<Setter Property="Icon" Value="{StaticResource myRectangle}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</TextBox.ContextMenu>
But this only displays the last rectangle:

A second option is to define a Rectangle in your ResourceDictionary with x:Shared set to False:
<ResourceDictionary>
<Rectangle x:Key="myRectangle" x:Shared="False" Width="20" Height="20" Fill="{Binding CategoryColor}" />
</ResourceDictionary>
...and then use that in your Style:
<TextBox>
<TextBox.ContextMenu>
<ContextMenu Focusable="False" ItemsSource="{Binding Categories}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding Name}"/>
<Setter Property="Focusable" Value="False"/>
<Setter Property="Icon" Value="{StaticResource myRectangle}" />
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
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