WPF 相对源 - 找不到与引用绑定的源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17142288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:01:22  来源:igfitidea点击:

WPF Relative source- Cannot find source for binding with reference

wpfbindinglistboxrelativesource

提问by Mateusz Dembski

have you ever have a problem like this:

你有没有遇到过这样的问题:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression:Path=DataContext; DataItem=null; target element is 'ContextMenu' (Name=''); target property is 'DataContext' (type 'Object')

Code:

代码:

<ContextMenu DataContext="{Binding Path=DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" 

Context Menu is in the:

上下文菜单位于:

ListBox-> ListBoxItemTemplate -> DataGrid -> DataGrid.ContextMenu

I have also another Binding in ListBox control, that works with no problems at all.

我在 ListBox 控件中还有另一个 Binding,它完全没有问题。

回答by Mateusz Dembski

The solution:

解决方案:

1) Set Tag property on ContextMenu owner to DataContext you wanted. 2) Set DataContext of ContextMenu to

1) 将 ContextMenu 所有者的 Tag 属性设置为您想要的 DataContext。2)将ContextMenu的DataContext设置为

DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}} 

3) Bind your elements like this:

3)像这样绑定你的元素:

Name_Of_Property="{Binding Tag.Name_Of_Property}"

回答by blindmeis

context menu is not part of the visual tree, so you use PlacementTarget within your binding

上下文菜单不是可视化树的一部分,因此您可以在绑定中使用 PlacementTarget

 <ContextMenu DataContext="{Binding Path=PlacementTarget.DataContext, RelativeSource=Self}" />

this would use the DataContext of the DataGrid

这将使用 DataGrid 的 DataContext