【问题标题】:WPF Context Menu won't Bind To VIewModel propertyWPF 上下文菜单不会绑定到 VIewModel 属性
【发布时间】:2017-12-04 18:28:37
【问题描述】:

我遇到了一个无法解决的 WPF 绑定问题。我有一个 ContextMenu 模板,其格式如下所示:

<ContextMenu x:Key="CopyPasteContextMenu">
    <MenuItem Header="AlternateDelete"
              Command="{Binding Path=PlacementTarget.Tag.DataContext.AlternateDeleteCommand, 
              RelativeSource={RelativeSource Self}, Mode=OneWay}"/>
</ContextMenu>

DataTemplat 中使用了上下文菜单,而 Border 上的 Tag 绑定正在正确找到 PropertyEditorView,我只是无法将它从边框获取到 contextmenu。

<DataTemplate x:Key="PropertyValueCellViewingTemplate" DataType="viewModels:IConfigurationItemViewModel">
    <Border x:Name="ValueCellBorder"
           Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type views:PropertyEditorView}}}"
           ContextMenu="{StaticResource CopyPasteContextMenu}"
           Style="{StaticResource PropertyGridValueCellBorderStyle}">
        (...)
    </Border>
</DataTemplate>

标签可以正确绑定到我称为“PropertyEditorViewModel”的视图模型。我可以在可视化树中调试系统时看到这一点。当我钻入我的上下文菜单时,绑定没有正确发生。

为了使我的命令正常工作,我需要将它正确绑定到名为“AlternateDeleteCommand”的 PropertyEditorView 视图模型命令。

public class PropertyEditorViewModel : DisposableViewModelBase, IPropertyEditorViewModel
{
    public ICommand AlternateDeleteCommand { get; set; }

到目前为止看了一天,不知道为什么我的绑定在上下文菜单上不起作用,有人得到我遗漏的东西吗?

谢谢!

【问题讨论】:

  • 我刚刚做了一个快速测试,发现 MenuItems 继承了上下文菜单目标的 DataContext ——例如,我希望 PropertyEditorViewModel 是 DataTemplate 的 DataContext ,因此如果 DataTemplate 中的 Border,然后在 MenuItem 中,Command="{Binding AlternateDeleteCommand}" 将起作用。
  • 如果对绑定失败(或似乎失败)的原因有疑问,请始终添加PresentationTraceSources.TraceLevel=High。每当绑定更新时,这将在运行时向 VS 输出窗格中输出多行调试信息。它会准确地告诉你它在做什么来查找它的源属性,如果它失败了,它会告诉你在哪里以及为什么。
  • 我确实按照 JM 下面的建议进行了尝试,并且成功了,所以我将它移回了数据模板中,一旦我将相对源设置为上下文菜单,它仍然有效。谢谢埃德!
  • 我认为您不需要任何我测试过我展示给您的案例的精心制作的东西。据我所知,你有一个非常复杂的方法来绑定你已经拥有的 DataContext 的属性。

标签: c# wpf binding contextmenu


【解决方案1】:

相对源不需要在上下文菜单上而不是在菜单项上吗?既然你在检查上下文菜单的放置目标?

<MenuItem Header="AlternateDelete"
          Command="{Binding Path=PlacementTarget.Tag.DataContext.AlternateDeleteCommand, 
          RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Mode=OneWay}" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 2014-07-20
    • 2013-09-23
    • 1970-01-01
    • 2019-02-28
    相关资源
    最近更新 更多