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

标签 wpf binding listbox relativesource

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

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/

相关文章:

vb.net - 更改列表框的颜色、突出显示、背景大小?

c# - 如何重新排列出现在任务栏中的应用程序的缩略图?

wpf - 单独的 View 模型中的主/详细信息?

wpf - 将字符串列表作为复选框绑定(bind)到 UI?

c# - wpf.DataGrid 中的自动行高

wpf - MVVM 和(动态地)从另一个组合框的值填充一个组合框

image - 从项目文件加载图像

c# - 如何单次同步两个列表?

c# - 绑定(bind)到元组列表

wpf - WPF 列表框中的 WindowsFormsHost 项目 - Z 顺序