gpt4 book ai didi

wpf - MVVM 绑定(bind)命令到上下文菜单项

转载 作者:行者123 更新时间:2023-12-03 13:42:06 26 4
gpt4 key购买 nike

我正在尝试将命令绑定(bind)到 WPF 中的菜单项。我正在使用与所有其他命令绑定(bind)相同的方法,但我不知道为什么它在这里不起作用。

我目前正在像这样绑定(bind)我的命令:

Command = "{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.MyCommand}"

这是出错的地方(这是在用户控件内)
<Button Height="40" Margin="0,2,0,0" CommandParameter="{Binding Name}" 
Command = "{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.ConnectCommand}">

<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Remove" CommandParameter="{Binding Name}"
Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.RemoveCommand}"/>
</ContextMenu>
</Button.ContextMenu>
...

第一个命令绑定(bind)正常工作,但第二个拒绝做任何事情。
我尝试更改祖先级别并命名我的控件以通过 ElementName 而不是 RelativeSource 来访问它,但仍然没有改变。它一直说“找不到引用绑定(bind)的来源......”

我错过了什么?

最佳答案

(编辑)由于您提到这是在 ItemsControl 的模板中,所以情况有所不同:

1) 从此博客获取 BindingProxy 类(并阅读博客,因为这是有趣的信息):How to bind to data when the DataContext is not inherited .

基本上,ItemsControl(或 ContextMenu)中的元素不是可视树或逻辑树的一部分,因此无法找到 UserControl 的 DataContext。很抱歉在这里没有写更多的内容,但是作者已经做得很好,一步一步地解释了它,所以我无法用几行来给出完整的解释。

2)做这样的事情:(您可能需要对其进行一些调整以使其在您的控制下工作):

一种。这将使您可以使用 StaticResource 访问 UserControl DataContext:

<UserControl.Resources>
<BindingProxy
x:Key="DataContextProxy"
Data="{Binding}" />
</UserControl.Resources>

湾。这使用 (a) 中定义的 DataContextProxy:
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Remove" CommandParameter="{Binding Name}"
Command="{Binding Path=Data.RemoveCommand, Source={StaticResource DataContextProxy}}"/>
</ContextMenu>

这在树和数据网格等方面对我们有用。

关于wpf - MVVM 绑定(bind)命令到上下文菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9994241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com