Is there an easy way to specify WPF data binding where the path is one β€œlevel” up?

This example is admittedly a bit contrived, but I'm 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 the LayoutRoot and DataGrid grid, where I want to access the Name property in the DataGrid instead of the alias properties, for example, in the second column:

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

It is intuitive how I try to associate the name, but of course it looks stupid. Is there something similar when specifying a path, or are you forced to get a relative source before the LayoutRoot data context. If you need, what is the most effective way?

+6
data-binding relative-path wpf
source share
2 answers

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 actions:

So that the source element is equal to the closest parent element of this type:

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

To make the source element equal to the nth nearest parent element of this type:

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

To make the source item equal to the previous data item in the data collection:

 {Binding RelativeSource={RelativeSource PreviousData}} 
+10
source share

I think there is no better way to do this than using a relative tree source. You can rewrite your model (for example, add a link to the parent Person from Alias ), but this is hardly the best fit.

In terms of performance, I have never encountered bottlenecks in relative source bindings. There is always something else that keeps the app from rocket speed.

0
source share

All Articles