c# - 在按钮单击上下文菜单中如何绑定(bind)到 viewModel?

标签 c# wpf data-binding mvvm contextmenu

我有一个单击该按钮打开上下文菜单的按钮,现在单击上下文菜单将绑定(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/

相关文章:

wpf - 在不属于数据绑定(bind)控件的控件中表示验证错误?

c# - String.Format 格式化数组

c# - 没有 DI 的单元测试遗留代码

c# - 获取用户在 MSAGL 中点击的 Vertex(Node) Object

DataGridTemplateColumn 中的 WPF 数据绑定(bind) ComboBox

javascript - 如何使用隔离范围提高 Angular Directive(指令)中双向绑定(bind)的性能?

c# - 如何在有外键的表中插入数据

c# - 无法加载文件或程序集或其依赖项之一 - 如何确切知道无法加载的内容?

wpf - XAML 文件 (WPF) 的编译

WPF单选按钮以奇怪的顺序触发转换器