你有没有遇到过这样的问题:
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')
代码:
<ContextMenu DataContext="{Binding Path=DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
上下文菜单位于:
ListBox-> ListBoxItemTemplate -> DataGrid -> DataGrid.ContextMenu
我在 ListBox 控件中还有另一个 Binding,它完全没有问题。
最佳答案
解决方案:
1) 将 ContextMenu 所有者上的 Tag 属性设置为您想要的 DataContext。
2) 将 ContextMenu 的 DataContext 设置为
DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}
3)像这样绑定(bind)你的元素:
Name_Of_Property="{Binding Tag.Name_Of_Property}"
关于WPF 相对源 - 找不到与引用绑定(bind)的源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17142288/