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

百般思念 提交于 2020-01-13 08:55:48

问题


This example is a admittedly a little contrived but I am doing something similar. Let's say I have the following simple classes:

public class Person
{
    public string Name { get; set; }
    public List<Alias> Aliases { get; set; }
}

public class Alias
{
    public string AliasName { get; set; }
}

And let's say that I have Xaml with a LayoutRoot grid, and a DataGrid where I want to access the Name property within the DataGrid instead of the Aliases properties like in the second column here:

<Grid x:Name="LayoutRoot" DataContext="PersonInstance">
    <DataGrid ItemsSource="{Binding Aliases}">
        <DataGrid.Columns>
            <data:DataGridTextColumn Header="AliasName" Binding="{Binding AliasName, Mode=TwoWay}"/>
            <data:DataGridTextColumn Header="Name" Binding="{Binding ../Name, Mode=TwoWay}"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

That is intuitively how I would attempt to bind the name, but needless to say that looks stupid. Is there something like that when specifying a path, or are you forced to get a relative source up to the LayoutRoot data context. If you have to, what's the most efficient way?


回答1:


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}}



回答2:


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.



来源:https://stackoverflow.com/questions/3012586/is-there-a-simple-way-to-specify-a-wpf-databinding-where-the-path-is-one-level

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