Skip to content

Antelcat/I18N

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

71 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Antelcat.{I18N}

给.NET应用程序提供响应式的多语言支持。

dotnet-version dotnet-version csharp-version nuget


🇬🇧 English

🗔 受支持的平台

📖 示例


静态使用

当你在项目中使用.resx文件作为语言文件时,你可以使用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 
{
}

然后在你的.xaml文件中使用x:Static来为你的控件提供资源键

如果你已经在你的.resx文件中有

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

你可以像这样使用:

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

然后你可以使用这个键来绑定语言源

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

当你想要改变语言时,只需要调用

using System.Windows;

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

你可以看到文本在语言之间变化。


动态使用

有时你的源文本并不是在你的应用程序中定义的,而是从其他来源(如网络)接收到的,你可以使用I18N直接绑定文本。

如果你收到了一个像这样的json:

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

并且你已经在.resx中将他翻译成了另一种语言

<data name="This is a message" xml:space="preserve">
    <value>这是一条消息</value>
</data>

你肯定会设计一个ViewModel并且将他设置到属性Message中,你可以像这样绑定:

<!--他的DataContext就是你的ViewModel-->
<TextBlock Text="{I18N {Binding Message}}"/> 

每当Message属性被改变或者语言源被改变时,文本都会自动更新。


多个文本组合和格式化

有些情况下,你需要将多个文本组合起来,或者对文本进行格式化,你可以使用I18NLanguageBinding来实现。

如果你已经有了如下翻译的.resx文件:

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

并且在.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 是字符串的模板,其中的 LanguageBindingBinding 会提供模板的参数,他们会被按顺序格式化成最终的文本。同时保持整体的响应性。