问题描述
我创建了一个自定义的上下文菜单,我在其中更改了所有项目的外观.这些项目包含不同的控件,如组合框和按钮.现在我希望菜单在按下按钮或选择组合框项目时关闭.目前菜单只是保持打开状态.能给个提示吗?
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.
更新
以下按钮(或任何其他控件)无需 Blend SDK 即可实现:
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>
推荐答案
使用 ChangePropertyAction
,它是 Blend SDK 以在单击按钮后立即更改 ContextMenu 的 IsOpen
属性:
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>
您需要以下命名空间:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ei="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"
这篇关于使用模板化菜单项关闭 ContextMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!