我有一个单击该按钮打开上下文菜单的按钮,现在单击上下文菜单将绑定(bind)到 viewModel。但它没有发生。
<Button Content="Copy" Tag="{Binding LinkViewModel, RelativeSource={RelativeSource Mode=Self}}" Command="{Binding LinkCopyCommand, UpdateSourceTrigger=PropertyChanged}" >
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy Download link " Command="{Binding Path=Parent.PlacementTarget.Tag.CopyViewCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}" />
<MenuItem ... />
</ContextMenu>
</Button.ContextMenu>
</Button>
我已经尝试过 tag 属性,但在我看来它不起作用。如果我绑定(bind)到按钮本身, View 模型工作正常,但 contextMenu 数据绑定(bind)不起作用。
编辑:
现在由于代码在讨论后工作,我想把它贴在这里。
我所做的更改是我把 UpdateSourceTrigger="Propertychanged"这里是代码
<Button Content="Copy" Tag="{Binding LinkViewModel, RelativeSource={RelativeSource Mode=Self}}" Command="{Binding LinkCopyCommand, UpdateSourceTrigger=PropertyChanged}" >
<Button.ContextMenu>
<ContextMenu Width="{Binding RelativeSource={RelativeSource Self}}">
<MenuItem Header="Copy View link " Command="{Binding CopyViewCommand, UpdateSourceTrigger=PropertyChanged}" />
<MenuItem ... />
</ContextMenu>
</Button.ContextMenu>
</Button>
但是我不知道它是怎么突然起作用的,在按钮上下文菜单的情况下它必须与标签属性一起使用。如果有人对此有所了解,我想很多像我这样的新 WPF 和数据绑定(bind)的人都会受益。
最佳答案
我假设您在 UserControl
中使用此按钮.请尝试以下代码
<Button Content="Copy" Tag="{Binding LinkViewModel, RelativeSource={RelativeSource Mode=Self}}" Command="{Binding LinkCopyCommand, UpdateSourceTrigger=PropertyChanged}" >
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy Download link " Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.CopyViewCommand}" />
<MenuItem ... />
</ContextMenu>
</Button.ContextMenu>
</Button>
关于c# - 在按钮单击上下文菜单中如何绑定(bind)到 viewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21595551/