【发布时间】: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