How to bind a DataGridRow element with a template in this row in xaml?

What binding is used to bind the element defined in the template of the DataGridTemplateColumn cell to the related data element of this DataGridRow cell?

For example, suppose the DataGrid elements are objects that have the Name property. What binding is required in the code below to bind a TextBlock Text to the "Name" property of the data item represented by the parent string?

(And yes, in the example I could just use a DataGridTextColumn, but I just simplify, for example, sake.)

<DataGrid ItemsSource="{Binding Items}"> <DataGrid.Columns> <DataGridTemplateColumn Header="Name"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding ???}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> 
+4
source share
1 answer

You do not need any special kind of binding - TextBlock inherits the datacontext from the string (which is specified by the associated element).

So you can just do this:

 <TextBlock Text="{Binding Name}" /> 

To see that the datacontext is actually inherited by the TextBlock, you can set another datacontext that is closer to the TextBlock in the control hierarchy. Now TextBlock will use this datacontext file.

In this example, the name of the StackPanel will be displayed in the TextBlock instead of the name in the linked row object in the DataGrid:

 <DataTemplate> <StackPanel x:Name="panel1" DataContext="{Binding RelativeSource={RelativeSource Self}}"> <!-- Binds to Name on the Stackpanel --> <TextBlock Text="{Binding Name}" /> <!-- Binds to Name on object bound to DataGridRow --> <TextBlock Text="{Binding DataContext.Name, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGridRow}}" /> </StackPanel> </DataTemplate> 
+4
source

Source: https://habr.com/ru/post/1443723/


All Articles