【问题标题】:How do I Programatically close ContextMenu如何以编程方式关闭 ContextMenu
【发布时间】:2016-03-08 09:36:12
【问题描述】:

有一个 ContextMenu 弹出,里面有一些控件:

<ContextMenu>
    <StackPanel Orientation="Vertical">
        <TextBox Text="{Binding Path=PlacementTarget.Tag.DataContext.AddFolderName, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"></TextBox>
        <Button Content="Create here"
            Command="{Binding Path=PlacementTarget.Tag.DataContext.AddFolderCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}">
        </Button>
    </StackPanel>
</ContextMenu>

当用户右键单击时,它会打开和关闭,一切都很好。但是,如果用户也按下按钮,我想关闭此菜单。

我之前使用按钮单击弹出窗口来完成此操作 - 如果用户单击按钮打开弹出窗口,您可以在执行的命令中设置一个 IsOpen 布尔属性,该属性设置为 true,从而显示弹出窗口。

但似乎没有一种等效的方法可以访问上下文菜单上的“菜单打开”功能。至少我找不到。谁能指出我正确的方向?

【问题讨论】:

    标签: c# wpf contextmenu


    【解决方案1】:

    There is an IsOpen in ContextMenu too. 您可以将它绑定到 ViewModel 中的属性,就像绑定 Command 一样,并让 AddFolderCommand 将该属性设置为 false。例如:

    <ContextMenu IsOpen="{Binding Path=PlacementTarget.Tag.DataContext.IsOpen, Mode=TwoWay
                 RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}">
    

    然后在AddFolderCommand.Execute 你可以做IsOpen = false

    这是提供 PlacementTarget.Tag.DataContext 实际上是您需要的 ViewModel。请注意ContextMenu 使用它自己的窗口来防止DataContext 继承。你有几个选择来解决这个问题:

    • 显式引用另一个元素或其DataContext,在绑定中使用ElementNameDataContext="{Binding ElementName=other, Path=DataContext}"/&gt;
    • 使用 Parent 属性访问声明 ContextMenu 的元素:{Binding Path=Parent.DataContext, RelativeSource={RelativeSource Self}}
    • 使用静态视图模型:DataContext={Binding Source={x:Static local:YourStaticViewModel}

    如果您不想从 ViewModel 执行此操作,则可以使用代码隐藏中的事件:只需为 ContextMenu 命名,以便您可以从代码隐藏中访问它,处理点击事件在按钮上,然后在事件处理程序上将 IsOpen 设置为 false。

    【讨论】:

    • 嗨。感谢您尝试提供帮助。我确实发现有一个 IsOpen 属性可以绑定。问题是我一直在使用按钮打开一个弹出窗口,所以我有一个命令函数,我可以在其中将 IsOpen 设置为 true。由于 contextmenu 是右键单击,我不知道在哪里将命令函数绑定到 XAML。
    • @MattThrower,如果我在这种情况下对您的理解正确,您的关注正在关闭,并且您已经有一个绑定到按钮的命令,您可以从该按钮执行关闭。您只需在该命令执行方法中将 IsOpen 设置为 false。
    【解决方案2】:

    您可以使用 Visibility 属性:

    myContextMenu.Visibility = Visibility.Collapsed;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 2015-11-26
      • 2020-07-08
      • 2013-07-04
      • 2010-11-17
      • 1970-01-01
      相关资源
      最近更新 更多