wpf - 使用模板化菜单项关闭 ContextMenu

标签 wpf xaml contextmenu controltemplate

我创建了一个自定义的上下文菜单,在其中更改了所有项目的外观。 这些项目包含不同的控件,例如组合框和按钮。现在,我希望在按下按钮或选择组合框项目时关闭菜单。目前菜单保持打开状态。 你能给我一点提示吗?

这是一个简化的代码,用于展示我所做的事情:

<ContextMenu StaysOpen="False">
    <MenuItem>
        <MenuItem.Template>
            <ControlTemplate>
                <Grid MinWidth="200">
                    <Button Command="{Binding SomeWorkingCommandBinding}">OK</Button>
                </Grid>
            </ControlTemplate>
        </MenuItem.Template>
    </MenuItem>
</ContextMenu>

如上所述,我想在点击“确定”按钮时关闭菜单。

更新

以下按钮(或任何其他控件)无需 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 属性:

<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"

关于wpf - 使用模板化菜单项关闭 ContextMenu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14007838/

相关文章:

c# - 为什么找不到我的 ResourceDictionary xaml 文件?

c# - 在 WPF 的静态资源中存储具有内容的元素

wpf - 使用 ItemContainerStyle 时如何在 ContextMenu 的 MenuItem 中设置图标

android - onContextItemSelected 未在 Fragment 中调用

wpf - TabControl 的每个选项卡上的不同 View /用户控件

c# - 将 bool 值绑定(bind)到 visualstate

c# - enter press 不会引发属性更改事件 wpf

c# - 计算 WriteableBitmap.WritePixels 方法所需的缓冲区大小

c# - 在 WPF 中重用 ToggleButton 样式

python - 子菜单项不调用函数 [有工作解决方案]