I use a ContextMenu with Buttons in it. Whenever the special Button is pressed I want the ContextMenu to be closed. I saw a possibility for a MenuItem which is called "StaysOpenOnClick".. this works perfectly fine.
This is what I need for the Button.. Especially a XAML only solution would be nice to have if anyone can help out!
Thanks in advance.
I'm not completely sure what you're after, but here is a context menu with a button:
<TextBlock
Text="Hello, world!">
<TextBlock.ContextMenu>
<ContextMenu x:Name="contextMenu">
<MenuItem>
<MenuItem.Header>
<Button Content="MyButton" Click="OnMenuButtonClick" />
</MenuItem.Header>
</MenuItem>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
If you handle the button click as follow, it will close the context menu:
private void OnMenuButtonClick(object sender, RoutedEventArgs e)
{
contextMenu.IsOpen = false;
}
(Not a XAML-only solution, though.)
You could close the ContextMenu by animating its IsOpen property using a BooleanAnimationUsingKeyFrames. This is a XAML only solution:
<Grid Background="Yellow" Width="50" Height="50">
<Grid.Resources>
<Storyboard x:Key="sb">
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</Grid.Resources>
<Grid.ContextMenu>
<ContextMenu x:Name="contextMenu">
<MenuItem>
<MenuItem.Header>
<Button Content="TheButton" Click="OnButtonClick" />
</MenuItem.Header>
</MenuItem>
<ContextMenu.Triggers>
<EventTrigger RoutedEvent="ButtonBase.Click">
<BeginStoryboard Storyboard="{StaticResource sb}" />
</EventTrigger>
</ContextMenu.Triggers>
</ContextMenu>
</Grid.ContextMenu>
</Grid>
This solution works, but the ContextMenu now gets closed for all buttons in my ContextMenu. I just wanted it to be closed with only one button called "Settings".
In this case you could set the SourceName property of the EventTrigger to the x:Name of the "Settings" Button:
<Grid Background="Yellow" Width="50" Height="50">
<Grid.Resources>
<Storyboard x:Key="sb">
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</Grid.Resources>
<Grid.ContextMenu>
<ContextMenu x:Name="contextMenu">
<MenuItem>
<MenuItem.Header>
<Button Content="Settings" x:Name="settingsButton" />
</MenuItem.Header>
</MenuItem>
<MenuItem>
<MenuItem.Header>
<Button Content="About" />
</MenuItem.Header>
</MenuItem>
<ContextMenu.Triggers>
<EventTrigger RoutedEvent="ButtonBase.Click" SourceName="settingsButton">
<BeginStoryboard Storyboard="{StaticResource sb}" />
</EventTrigger>
</ContextMenu.Triggers>
</ContextMenu>
</Grid.ContextMenu>
</Grid>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.