I have a MenuItem in a context menu which I want to generate sub MenuItems for each item in a list using the ItemSource. Each of these generated items should then also have sub MenuItems Active (checkable), Edit and Delete.
Custom Messages
-Custom Message 1
-Active
-Edit
-Delete
-Custom Message 2
-Active
-Edit
-Delete
-Custom Message 3
-Active
-Edit
-Delete
The following XAML partially works:
<MenuItem Header="Custom Messages" Visibility="{Binding Path=HasCustomMessages, Converter={StaticResource BVC}}" ItemsSource="{Binding Path=CustomMessages}" DisplayMemberPath="Description">
<MenuItem.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="ItemsSource">
<Setter.Value>
<x:Array Type="FrameworkElement">
<MenuItem Header="Active" IsCheckable="True" IsChecked="{Binding Path=Active}"></MenuItem>
<Separator></Separator>
<MenuItem Header="Edit" Name="EditCustomMessageButton" Click="EditCustomMessageButton_Click" Style="{x:Null}"></MenuItem>
<MenuItem Header="Delete" Name="DeleteCustomMessageButton" Click="DeleteCustomMessageButton_Click" Style="{x:Null}"></MenuItem>
</x:Array>
</Setter.Value>
</Setter>
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
<MenuItem Header="Add Custom Message" Name="AddCustomMessageButtton" Click="AddCustomMessageButtton_Click"></MenuItem>
<Separator></Separator>
<MenuItem Header="Delete" Name="DeleteButton" Click="DeleteButton_Click"></MenuItem>
However there are two problems:
Edit and Delete seems to be behaving in a recusive manner as they both appear to have sub menus and subsequently throw and exception when hovered over:
By setting ItemSource="{x:Null}" on Edit and Delete this solves the above problem but the events behave strangly. Clicking Delete does nothing and clicking Edit triggers the Edit button click event followed by the Delete button click event and then the Add button click event (which isn't even a sibling of the other two).
The problem is that you set the style of all MenuItem
to be the same with the submenu, which cause this infinite recursion hence - StackOverflow :-) issue.
The following line is wrong:
<Style TargetType="MenuItem">
So instead you can create this style in your resources and call it by its x:Key:
<Style x:Key="SubMenuStyle">
<Setter Property="ItemsSource">
<Setter.Value>
<x:Array Type="FrameworkElement">
<MenuItem Header="Active" IsCheckable="True" IsChecked="{Binding Path=Active}"></MenuItem>
<Separator></Separator>
<MenuItem Header="Edit" Name="EditCustomMessageButton" Click="EditCustomMessageButton_Click" Style="{x:Null}"></MenuItem>
<MenuItem Header="Delete" Name="DeleteCustomMessageButton" Click="DeleteCustomMessageButton_Click" Style="{x:Null}"></MenuItem>
</x:Array>
</Setter.Value>
</Setter>
</Style>
<MenuItem Header="Custom Messages" ItemsSource="{Binding Path=CustomMessages}" ItemContainerStyle="{StaticResource SubMenuStyle}"...>
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