user1017477
user1017477

Reputation: 161

DataGrid - Change Column Header at Runtime

I am currently working on a multilingual app where the interface text can be swapped at runtime based on the language that is selected by the user. I am using DynamicResources defined in a ResourceDictionary and swapping the dictionary file when the language is changed. This works great for everything except for the DataGrid's Column Header property. I know that the DataGrid column is not part of the Visual Tree and have used proxies for binding to properties in my VM in the past however, in this case there is no binding to the VM. How can I go about updating the column headers when the ResourceDictionary is swapped?

My method for swapping dictionaries is below. This resides in the Application.xaml.vb and is called upon app startup passing a string saved in MySettings.Default. This is also called using a messenger from a property in a VM that is bound to a ComboBoxSelectedIndex.

Private Sub SetLanguage(ByVal language As String)
    Dim dic As ResourceDictionary = Nothing
    Dim langFile As String = Environment.CurrentDirectory & "\Languages\" & language & ".xaml"
    If File.Exists(langFile) Then
        Using fs As FileStream = New FileStream(langFile, FileMode.Open)
            dic = CType(XamlReader.Load(fs), ResourceDictionary)
            If LanguageCount > 0 Then
                    Resources.MergedDictionaries.RemoveAt(Resources.MergedDictionaries.Count - 1)
            End If
            Resources.MergedDictionaries.Add(dic)
        End Using
    End If
    LanguageCount += 1
End Sub

The related DataGrid xaml

<DataGridTextColumn Header="{DynamicResource G_Spec}" ... />

The ResourceDictionary entry

<system:String x:Key="G_Spec">Spec:</system:String>

Upvotes: 4

Views: 1913

Answers (1)

XAMeLi
XAMeLi

Reputation: 6289

This is an extremely simplified example, basically you can use HeaderTemplate for the column:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{DynamicResource MyColumnHeaderText}" />
        </DataTemplate>
    </DataGridTemplateColumn.HeaderTemplate>
</DataGridTemplateColumn>

Upvotes: 6

Related Questions