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

WPF相对源-找不到与引用绑定的源,wpf,binding,listbox,relativesource,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

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

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')
代码:


我在ListBox控件中还有另一个绑定,可以毫无问题地工作。

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

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

这将使用DataGrid的DataContext解决方案:

1) 将ContextMenu owner上的标记属性设置为所需的DataContext。 2) 将ContextMenu的DataContext设置为

DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}} 
3) 按如下方式绑定元素:

Name_Of_Property="{Binding Tag.Name_Of_Property}"

如果我必须更改placement标签,因为我必须知道我点击了列表框上的哪个项目?这真的很奇怪,因为在我的代码的另一部分中,ContextMenu上带有祖先的解决方案是有效的,但这里没有。PlacementTargetr的解决方案可行,但它并不能解决我的问题,因为我需要ListBox或更高版本的DataContext。您也可以使用StaticResourceSce作为绑定的源,那么您不需要在allor上使用RelativeSource,或者使用PlacementTarget的Tag属性将其绑定到所需的Datacontext,并将路径更改为PlacementTarget.Tag.DataContextOk,有一种从ContextMenu绑定到祖先的解决方案,但是我没有足够的分数来回答我自己关于stackoverflow的问题:d1)将ContextMenu所有者上的标记属性设置为所需的DataContext。2) 将ContextMenu的DataContext设置为DataContext=“{Binding PlacementTarget,RelativeSource={RelativeSource Self}}}3)如下绑定元素:Name_of_Property=“{Binding Tag.Name_of_Property}”
DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}} 
Name_Of_Property="{Binding Tag.Name_Of_Property}"