I18N

Reactive language support for WPF/Avalonia applications when using .resx file.

MIT License

Stars
60
Committers
1

Antelcat.{I18N}

Reactive language support for .NET applications.


πŸ‡¨πŸ‡³ δΈ­ζ–‡η‰ˆ

πŸ—” Supported Platforms

πŸ“– Sample

Static using

When using .resx language file in your project, you can automatically generate resource keys by using Antelcat.I18N.Attributes.ResourceKeysOfAttribute:

using Antelcat.I18N.Attributes;

namespace MyProject

//Auto generated class should be partial
[ResourceKeysOf(typeof(My.Resource.Designer.Type))]
public partial class LangKeys 
{
}

Then in your .xaml file you can use x:Static to provide resource key to your control

if you already have

<data name="Language" xml:space="preserve">
    <value>Language</value>
</data>

in your .resx file, you can use it like this:

<TextBolck Text="{x:Static myProject:LangKeys.Language}"/>

Then you can use the key to bind the language source using I18N

<TextBlock Text="{I18N {x:Static myProject:LangKeys.Language}}"/>

When you want to change the language, just call

using System.Windows;

I18NExtension.Culture = new CultureInfo("language code");

You can see the text is changing among the languages.


Dynamic using

Sometimes your source text is not defined in your application but received from other source like network, you can use I18N to bind the text directly.

If you receive a json like this:

{
    "message": "This is a message"
}

and you have translated it into another language in .resx like

<data name="This is a message" xml:space="preserve">
    <value>θΏ™ζ˜―δΈ€ζ‘ζΆˆζ―</value>
</data>

then you put the json into a Message property in your view model, you can bind it like this:

<!--whose DataContext is your view model-->
<TextBlock Text="{I18N {Binding Message}}"/> 

Each time when the Message property is changed or the language source is changed, the text will be updated automatically.


Combination and StringFormat

Somebody may want to combine several language sources into one text, you can also use I18N and LanguageBinding to do this

If you have source text in .resx file like this:

<data name="Current_is" xml:space="preserve">
    <value>ε½“ε‰ηš„ {0} 是 {1}</value>
</data>
<data name="Language" xml:space="preserve">
    <value>语言</value>
</data>
<data name="Chinese" xml:space="preserve">
    <value>δΈ­ζ–‡</value>
</data>

and in .xaml

<TextBlock>
    <TextBlock.Text>
        <I18N Key="{x:Static myProject:LangKeys.Current_is}">
            <LanguageBinding Key="{x:Static myProject:LangKeys.Language}"/>
            <Binding Path="Language"/> <!--source text from view model-->
        </I18N>
    </TextBlock.Text>
</TextBlock>

I18N.Key is the string template, content accepts LanguageBinding and Binding to provide the args.