Is there a simple way to specify a WPF databinding where the path is one “level” up?

99封情书 提交于 2019-12-05 02:57:45

This should work for you :

<DataGridTextColumn Header="Name" 
                    Binding="{Binding RelativeSource={RelativeSource 
                                                      FindAncestor,
                                                      AncestorLevel=3, 
                                                      AncestorType={x:Type Grid},
                                                      Mode=FindAncestor},
                                                    Path=DataContext.Name}"/>

You can use any of the following :

To make the source element equal the closest parent of a given type:

{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type
desiredType}}}

To make the source element equal the nth closest parent of a given type:

{Binding RelativeSource={RelativeSource FindAncestor,
AncestorLevel=n, AncestorType={x:Type desiredType}}}

To make the source element equal the previous data item in a data-bound collection:

{Binding RelativeSource={RelativeSource PreviousData}}

I think there is no better way to do this than using relative source up the tree. You could rewrite your model (for example, add a reference to parent Person from Alias) but that's hardly better approach.

From performance prospective I never found bottlenecks in relative source bindings. There's always something else that keeps your app away from rocket speed.

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