WPF: regarding the binding inside of DataGridTextColumns
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&g开发者_StackOverflow中文版t;
</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?
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
精彩评论