WPF Relative source- Cannot find source for binding with reference

白昼怎懂夜的黑 提交于 2020-01-02 08:44:23

问题


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.


回答1:


The solution:

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

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

3) Bind your elements like this:

Name_Of_Property="{Binding Tag.Name_Of_Property}"



回答2:


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

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

this would use the DataContext of the DataGrid



来源:https://stackoverflow.com/questions/17142288/wpf-relative-source-cannot-find-source-for-binding-with-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!