WPF: regarding the binding inside of DataGridTextColumns

1.6k Views Asked by At

Today I noticed a strange behavior regarding binding the header of a DataGridColumn to the ViewModel.

The following binding works perfectly (name of the DataGrid is MyGrid):

<DataGridTextColumn Binding="{Binding Name}"  Width="*" CanUserReorder="False" CanUserResize="False" IsReadOnly="True">
                                <DataGridTextColumn.HeaderTemplate>
                                    <DataTemplate>
                                        <TextBlock Text="{Binding ElementName=MyGrid, Path=DataContext.MyDeviceViewModel.CategoryHeader}"/>
                                    </DataTemplate>
                                </DataGridTextColumn.HeaderTemplate>
 </DataGridTextColumn>

Whereas the following does not work (it complains that MyGrid cannot be found):

<DataGridTextColumn Binding="{Binding Name}"  Width="*" CanUserReorder="False" CanUserResize="False" IsReadOnly="True">
    <DataGridTextColumn.Header>
        <TextBlock Text="{Binding ElementName=MyGrid, Path=DataContext.MyDeviceViewModel.CategoryHeader}"/>
    </DataGridTextColumn.Header>
</DataGridTextColumn>

What is the difference between binding to the viewmodel in the Template or in the UIElement directly?

1

There are 1 best solutions below

0
On

This should work

<TextBlock Text="{Binding MyDeviceViewModel.CategoryHeader}"/>

You don't need to refer the ElementName property when you are in the same control

HTH