VegaBrothers
VegaBrothers

Reputation: 126

Reading special characters from dynamic source in WPF

I am using a dynamic source to update my texts, it works perfect for normal character however for special characters like Chinese it only works if I directly put them in xaml file. It won't work if it is loaded dynamically.

<Button Style="{StaticResource DefBtn}" x:Name="button_CreateElement" Content="{DynamicResource CMMsg_5171}"  Click="button_CreateElement_Click"/>
<Button Style="{StaticResource DefBtn}" x:Name="button_DeleteElement" Content="删除" Click="button_DeleteElement_Click"/>

Here how it is rendered.

enter image description here

As you can see the dynamically loaded one is wrong.

Upvotes: 0

Views: 519

Answers (1)

Fredrik
Fredrik

Reputation: 2317

This worked for me:

<Window ... >

<!-- 
<Window.Resources>
    <clr:String x:Key="CMMsg_5171">删除</clr:String>
</Window.Resources> 
-->

<StackPanel>
    <TextBlock Text="{DynamicResource CMMsg_5171}" />
    <TextBlock Text="删除" />
</StackPanel>

UPDATE:

"loading the strings from an external file. Would that work as well?"

Yes. I added a resource dictionary ChineseTranslations.xaml (you could have one for each language), by right-click on project, Add, Resource Dictionary... Build Action was set to 'Content' and 'Copy Always'.

<ResourceDictionary ... xmlns:clr="clr-namespace:System;assembly=mscorlib" >

    <clr:String x:Key="CMMsg_5171">删除</clr:String>
    <!--more to come...-->
</ResourceDictionary>

And I added this resource dictionary to the merged dictionaries in the following manner:

public MainWindow()
{
    InitializeComponent();
    LoadTranslations();
}

private void LoadTranslations()
{
    string file = GetTranslationsFileForSelectedLanguage();

    using (FileStream stream = File.OpenRead(file))
    {
        System.Windows.Markup.XamlReader reader = new System.Windows.Markup.XamlReader();
        ResourceDictionary myResourceDictionary = (ResourceDictionary)reader.LoadAsync(stream);
        Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);
    }
}

private string GetTranslationsFileForSelectedLanguage()
{
    // todo: add selection logic for when we have more languages in the future
    return "ChineseTranslations.xaml";
}

Upvotes: 2

Related Questions