I have created a customized Context menu where I changed the appearance of all items. These Items contain different controls like comboboxes and buttons. Now I want the menu to close if a button was pressed or a combobox item was selected. Currently the menu just remains open. Can you give me a hint?
This is a simplified code to show what I did:
<ContextMenu StaysOpen="False">
<MenuItem>
<MenuItem.Template>
<ControlTemplate>
<Grid MinWidth="200">
<Button Command="{Binding SomeWorkingCommandBinding}">OK</Button>
</Grid>
</ControlTemplate>
</MenuItem.Template>
</MenuItem>
</ContextMenu>
As mentioned, I would like to close the menu when I hit that OK button.
UPDATE
The following button (or any other control) does the trick without the need of Blend SDK:
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(ContextMenu.IsOpen)" Storyboard.Target="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ContextMenu}}">
<DiscreteObjectKeyFrame KeyTime="0:0:0">
<DiscreteObjectKeyFrame.Value>
<sys:Boolean>False</sys:Boolean>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
Use the ChangePropertyAction
which is part of the Blend SDK to change the IsOpen
property of the ContextMenu as soon as the Button is clicked:
<ContextMenu x:Name="MyContextMenu">
<MenuItem>
<MenuItem.Template>
<ControlTemplate>
<Grid MinWidth="200">
<Button Command="{Binding SomeWorkingCommandBinding}" Content="OK">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:ChangePropertyAction TargetObject="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ContextMenu}}" PropertyName="IsOpen" Value="False"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>
</ControlTemplate>
</MenuItem.Template>
</MenuItem>
</ContextMenu>
You'll need the following namespaces:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ei="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"
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