tags:

views:

35

answers:

1

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>
            <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?

A: 

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.

Alex Lo
How does this work? The information in the headers is obtained from properties on the ViewModel (which is bound to the Grid DataContext), noe from a static source (like a header information provider)
Marius
where do you create the Grid's DataContext though? the alternative i mentioned (creating the column definitions in the CS file, not XAML) might be better for you.
Alex Lo
here are two decent resources about doing dynamic column creation: http://elegantcode.com/2010/03/08/silverlight-datagrid-populate-dynamic-columns-from-a-child-collection/ AND http://www.silverlightshow.net/items/Defining-Silverlight-DataGrid-Columns-at-Runtime.aspx
Alex Lo