WPF相对源-无法找到引用绑定的源

3
你是否曾经遇到过这样的问题:
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控件中还有另一个绑定,完全没有问题。

2个回答

8
解决方案: 1) 将ContextMenu所有者的Tag属性设置为所需的DataContext。 2) 将ContextMenu的DataContext设置为。
DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}} 

3)将您的元素绑定如下:

Name_Of_Property="{Binding Tag.Name_Of_Property}"

4

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

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

这将使用DataGrid的DataContext。

如果我必须更改放置标记,因为我需要知道我已单击的ListBox上的哪个项目呢? - Mateusz Dembski
这真的很奇怪,因为在我的代码的另一部分,使用 Ancestor 在 ContextMenu 上的解决方案有效,但是在这里却不行。使用 PlacementTarget 的解决方案可行,但这并不是我的问题的解决方案,因为我需要来自 ListBox 或更高层次的 DataContext。 - Mateusz Dembski
你也可以使用StaticResource作为绑定的源,这样你就不需要使用RelativeSource了。 - blindmeis
或者您可以使用PlacementTarget的Tag属性将其绑定到所需的DataContext,并将路径更改为PlacementTarget.Tag.DataContext。 - blindmeis
好的,有一种解决方案可以从ContextMenu绑定到Ancestor,但我没有足够的分数在stackoverflow上回答自己的问题:D 1)在ContextMenu所有者上设置Tag属性为所需的DataContext。 2)将ContextMenu的DataContext设置为DataContext =“{Binding PlacementTarget,RelativeSource = {RelativeSource Self}}” 3)像这样绑定您的元素:Name_Of_Property =“{Binding Tag.Name_Of_Property}” - Mateusz Dembski
请随意编辑我的答案,或者只需编辑您的问题并在那里添加您的答案。 - blindmeis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接