Josh
Josh

Reputation: 1630

Binding DataGrid column headers in Silverlight

I've seen quite a few unanswered posts on this topic, yet I'm still inclined to believe someone on here as figured this out and is holding out on the rest of us.

I have a DataGrid that contains a mix of template columns and text columns. I just need a way of binding the headers to properties in the viewmodel so that I can use different strings for different languages.

I've seen WPF datagrid header text binding and every post linked from it. None of the methods suggested here work in Silverlight.

Does no one have any ideas?

Upvotes: 2

Views: 1223

Answers (1)

Dane Creighton
Dane Creighton

Reputation: 11

I've recently spent a bit of time working on this too, here is how I got it working for other peoples benefit.

First declare namespace up top so I can specify it short hand in the xaml.

xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

Then I declare header styles as static resources up top to keep the datagrid xaml clean:

<navigation:Page.Resources>        
    <Style x:Key="NameStyle" TargetType="sdk:DataGridColumnHeader">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=LocalizedStrings.Name, Source={StaticResource Language}}"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style x:Key="DescriptionStyle" TargetType="sdk:DataGridColumnHeader">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=LocalizedStrings.Description, Source={StaticResource Language}}"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</navigation:Page.Resources>

Then in your datagrid xaml you can simply set your DataGridTextColumns Header style to your static resource header style.

<sdk:DataGrid.Columns>
    <sdk:DataGridTextColumn Width="Auto" FontSize="11" MinWidth="100" Binding="{Binding Name}" HeaderStyle="{StaticResource NameStyle}" />
    <sdk:DataGridTextColumn Width="1*" FontSize="11" Binding="{Binding Description}" HeaderStyle="{StaticResource DescriptionStyle}" />
</sdk:DataGrid.Columns>

My original solution was from this post: Dynamically setting the Header text of a Silverlight DataGrid Column

Just tidied it up a bit as I had 15 column headers to set.

Upvotes: 1

Related Questions