![](/img/trans.png)
[英]How can I bind a Hold/DoubleTap event of a button to a property in ViewModel
[英]In Button Click Context Menu How do I bind to viewModel?
我有一个按钮,单击该按钮会打开一个上下文菜单,现在单击上下文菜单将绑定到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>
我已经尝试了标签属性,但在我看来它不起作用。 如果绑定到按钮本身,则viewmodel可以正常工作,但是contextMenu dataBinding无法正常工作。
编辑:
现在,由于代码在讨论之后正在工作,我想将其发布在这里。
我所做的更改是,我将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>
但是我不知道它怎么突然起作用,在Button Context菜单的情况下它必须与tag属性一起工作。 如果有人对此有所了解,我认为许多像我这样的人都是新的WPF和数据绑定的受益者。
我假设您正在UserControl
中使用此Button。 请尝试以下代码
<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>
<Button Content="Copy" Command="{Binding LinkCopyCommand, UpdateSourceTrigger=PropertyChanged}" >
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy Download link " Command="{Binding Path=CopyViewCommand}" />
<MenuItem ... />
</ContextMenu>
</Button.ContextMenu>
直接从您的DataContext
...(即ViewModel)绑定CopyViewCommand
。
您必须将ContextMenu的DataContext设置为ViewModel。 一种方法是为上下文菜单设置一个Opened事件处理程序。
在下面的链接中查看我的答案-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.