[英]WPF Databinding with RelativeSource and AncestorType
I am trying to get some binding code working. 我试图让一些绑定代码工作。 Bascially I want to bind the IsEnabled property of an element of my grid's context menu with a value of the selected row in the grid.
基本上我想将网格上下文菜单元素的IsEnabled属性与网格中选定行的值绑定。
I have it working with this: 我有这个工作:
<my:DataGrid.ContextMenu>
<ContextMenu DataContext="{Binding PlacementTarget.SelectedItem, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Grant Access" IsEnabled="{Binding Connectable}"/>
</ContextMenu>
</my:DataGrid.ContextMenu>
But I want to do it this way and it's not working. 但是我想这样做而且它不起作用。 It doesn't error but just doesn't disable the menu item.
它没有错误,但只是不禁用菜单项。 Any idea why?
知道为什么吗?
<my:DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Grant Access" IsEnabled="{Binding Path=SelectedItem.Connectable, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type my:DataGrid}}}"/>
</ContextMenu>
</my:DataGrid.ContextMenu>
Try using ElementName binding
instead of Ancestor binding
. 尝试使用
ElementName binding
而不是Ancestor binding
。 ContextMenu
is not part of Grid's visual tree. ContextMenu
不是Grid的可视化树的一部分。
--edit-- - 编辑 -
Ah, I was wrong. 啊,我错了。 ElementName binding (example given below) would also not work with ContextMenu.
ElementName绑定(下面给出的示例)也不适用于ContextMenu。 It is not part of DataGrid's visual tree.
它不是DataGrid可视化树的一部分。 That is why it cannot see that DataGrid and thus cannot reference it.
这就是为什么它无法看到DataGrid因此无法引用它。 You will have to do it using the first method.
您将不得不使用第一种方法。
Any reason why you don't want to do it that way? 你有什么理由不想这样做吗?
<DataGrid.ContextMenu>
<ContextMenu DataContext="{Binding SelectedItem, ElementName=DataGrid1}">
<MenuItem Header="Grant Access"
IsEnabled="{Binding Connectable}" />
</ContextMenu>
</DataGrid.ContextMenu>
如果在调试模式下查看Visual Studio中的输出窗口,您将获得绑定错误的详细信息 - 这可能会对您的问题有所了解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.