views:

24

answers:

1

Hello,

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?

Thank you, Kevin

A: 

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

Avatar