开发者

How to bind from DataGridColumn.Header to ViewModel property?

I want to bind my datagrid header to a property on the DataContext of the grid. Now, I got it to work, but I consider this a temporarily solution:

    <DataGrid x:Name="grid" ItemsSource="{Binding Path=Items}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            &开发者_StackOverflow中文版lt;DataGridTextColumn Binding="{Binding Path=Description}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding ElementName=grid, Path=DataContext.ItemsUnit}"></TextBlock>
                    </DataTemplate>

The biggest issue with this solution is that it makes the binding more fragile (context sensitive). If the DataContext of the grid is used in a master/detail scenario (which makes the DataContext a BindingList instead of a single item) I would have to replace update the DataGrid DataContext with DataContext={Binding /}.

Is there a more robust way to bind from the DataGrid.HeaderTemplate than using ElementName and refering to the DataContext?


One simple solution would be to use a named resource

<UserControl.Resources>
  <ResourceDictionary>
    <MyNamespace:MyHeaderProvider x:Key="MyHeaderProvider">
  </ResourceDictionary>
</UserControl.Resources>

...

Header="{Binding Path=HeaderText, Source={StaticResource MyHeaderProvider}"

If everything is really dynamic this may not work. When I made a grid with more dynamic/data driven columns I did not define them in XAML but generated them in the code behind, where you don't have to do relative DataContext.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜