• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

GuOrg/Gu.Localization

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

GuOrg/Gu.Localization

开源软件地址(OpenSource Url):

https://github.com/GuOrg/Gu.Localization

开源编程语言(OpenSource Language):

C# 98.0%

开源软件介绍(OpenSource Introduction):

Gu.Localization.

Join the chat at https://gitter.im/JohanLarsson/Gu.Localization License Build status Build Status NuGet NuGet

Contents.

Quickstart

  1. PM> Install-Package Gu.Wpf.Localization or search for Gu.Wpf.Localization in the Manage NuGet Packages tab.
  2. Create a new resource from Project > Properties > Resources and name it Resources.<tag>.resx. Example: Resources.ru-RU.resx To see all convention tags you can check them here
  3. Use the markup extension like this:
<Window
    x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:localize="http://gu.se/Localization"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:properties="clr-namespace:WpfApp1.Properties"
    Title="MainWindow"
    mc:Ignorable="d">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <localize:LanguageSelector AutogenerateLanguages="True" />
        <TextBlock Grid.Column="1" Text="{localize:Static properties:Resources.Some_text}" />
    </Grid>
</Window>

Renders:

Localize

Text="{localize:Static properties:Resources.Some_text}" will be the translated text based on the current culture.

Note: If you get errors about missing localize:Static when adding this, clean and rebuild your solution from Build > Clean Solution and Build > Rebuild Solution respectively.

Note: To set the translation programmatically write: Translator.Culture = CultureInfo.GetCultureInfo("ru-RU"); To use a neutral language (aka Resources.resx), simply add [assembly:NeutralResourcesLanguageAttribute("en")] in your AssemblyInfo.cs file found in your project.

Note: Make sure to add xmlns:properties="clr-namespace:YourApp.Properties" and xmlns:localize="http://gu.se/Localization" in your xaml.

Note: Intsall Gu.Wpf.Localization in the application project. The library is split in Gu.Wpf.Localization and Gu.Localization so that usage in domain projects does not require adding WPF dependencies.

For working with resx in Visual Studio ResXManager is a nice extension.

NeutralResourcesLanguage

Adding:

[assembly:NeutralResourcesLanguage("en")]

To AsseblyInfo.cs or anywhere else tells Gu.Localization what language to use for the neutral resource. It prevents some duplication. See: NeutralResourcesLanguageAttribute

Usage in XAML.

The library has a StaticExtension markupextension that is used when translating. The reason for naming it StaticExtension and not TranslateExtension is that Resharper provides intellisense when named StaticExtension Binding the text like below updates the text when Translator.CurrentCulturechanges enabling runtime selection of language.

The markupextension has ErrorHandling = ErrorHandling.ReturnErrorInfoPreserveNeutral as default, it encodes errors in the result, see ErrorFormats)

Simple example

For each language, create a resource.xx.resx file. You can use ResXManager to do this for you.

<UserControl ...
             xmlns:l="clr-namespace:Gu.Wpf.Localization;assembly=Gu.Wpf.Localization"
             xmlns:p="clr-namespace:AppNamespace.Properties"
             xmlns:local="clr-namespace:YourNamespace;assembly=Gu.Localization">
    ...
    <!-- Dropbownbox to select a language -->
    <ComboBox x:Name="LanguageComboBox"
              ItemsSource="{Binding Path=(localization:Translator.Cultures)}"
              SelectedItem="{Binding Path=(localization:Translator.Culture),
                                              Converter={x:Static l:CultureOrDefaultConverter.Default}}" />

    <!-- Label that changes translation upon language selection -->
    <Label Content="{l:Static p:Resources.ResourceKeyName}" />

With converter

When StaticExctension is used for setting Binding.Source it returns an ITranslation, this means it can be used with a converter like below.

<TextBlock Text="{Binding Source={l:Static p:Resources.TranslatedToAll}, Path=Translated, Converter={x:Static local:StringToUpperConverter.Default}}" />
[ValueConversion(typeof(string), typeof(string))]
public sealed class StringToUpperConverter : IValueConverter
{
    public static readonly StringToUpperConverter Default = new StringToUpperConverter();

    public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value switch
        {
            string { } s => s.ToUpper(culture),
            null => null,
            _ => throw new ArgumentException($"Expected a string, was: {value.GetType()} with value: {value}"),
        };
    }

    object IValueConverter.ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new System.NotSupportedException($"{nameof(StringToUpperConverter)} can only be used in OneWay bindings");
    }
}

Bind a localized string.

<Window ...
        xmlns:p="clr-namespace:Gu.Wpf.Localization.Demo.WithResources.Properties"
        xmlns:l="http://gu.se/Localization">
    ...
    <TextBlock Text="{l:Static p:Resources.SomeResource}" />
    <TextBlock Text="{l:Enum ResourceManager={x:Static p:Resources.ResourceManager},
                             Member={x:Static local:SomeEnum.SomeMember}}" />
    ...

The above will show SomeResource in the Translator.CurrentCulture and update when culture changes.

Errorhandling.

By setting the attached property ErrorHandling.Mode we override how translation errors are handled by the StaticExtension for the child elements. When null the StaticExtension uses ReturnErrorInfoPreserveNeutral

<Grid l:ErrorHandling.Mode="ReturnErrorInfo"
     ...   >
    ...
    <TextBlock Text="{l:Static p:Resources.SomeResource}" />
    <TextBlock Text="{l:Enum ResourceManager={x:Static p:Resources.ResourceManager},
                             Member={x:Static local:SomeEnum.SomeMember}}" />
    ...

CurrentCulture.

A markupextension for accessing Translator.CurrentCulture from xaml. Retruns a binding that updates when CurrentCulture changes.

<Grid numeric:NumericBox.Culture="{l:CurrentCulture}"
     ...   >
    ...
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Effective culture: " />
            <TextBlock Text="{l:CurrentCulture}" />
        </StackPanel>
    ...

Binding to Culture and Culture in XAML.

The static properties support binding. Use this XAML for a twoway binding:

<Window ...
        xmlns:localization="clr-namespace:Gu.Localization;assembly=Gu.Localization">
    ...
<TextBox Text="{Binding Path=(localization:Translator.Culture)}" />

Usage in code.

The API is not super clean, introducing a helper like this can clean things up a bit.

Creating it like the above is pretty verbose. Introducing a helper like below can clean it up some. The analyzer checks calls to this method but it assumes:

  1. That the class is named Translate
  2. That the namespace the class is in has a class named Resources
  3. That the first argument is of type string.
  4. That the return type is string or ITranslation
namespace YourNamespace.Properties
{
    using Gu.Localization;
    using Gu.Localization.Properties;

    public static class Translate
    {
        /// <summary>Call like this: Translate.Key(nameof(Resources.Saved_file__0_)).</summary>
        /// <param name="key">A key in Properties.Resources</param>
        /// <param name="errorHandling">How to handle translation errors like missing key or culture.</param>
        /// <returns>A translation for the key.</returns>
        public static string Key(string key, ErrorHandling errorHandling = ErrorHandling.ReturnErrorInfoPreserveNeutral)
        {
            return TranslationFor(key, errorHandling).Translated;
        }

        /// <summary>Call like this: Translate.Key(nameof(Resources.Saved_file__0_)).</summary>
        /// <param name="key">A key in Properties.Resources</param>
        /// <param name="errorHandling">How to handle translation errors like missing key or culture.</param>
        /// <returns>A translation for the key.</returns>
        public static ITranslation TranslationFor(string key, ErrorHandling errorHandling = ErrorHandling.ReturnErrorInfoPreserveNeutral)
        {
            return Gu.Localization.Translation.GetOrCreate(Resources.ResourceManager, key, errorHandling);
        }
    }
}

Translator.

Culture.

Get or set the current culture. The default is null Changing culture updates all translations. Setting culture to a culture for which there is no translation throws. Check ContainsCulture() first.

Culture.

Get or set the current culture. The default is null Changing culture updates all translations. Setting culture to a culture for which there is no translation throws. Check ContainsCulture() first.

CurrentCulture.

Get the culture used in translations. By the following mechanism:

  1. CurrentCulture if not null.
  2. Any Culture in matching by name.
  3. Any Culture in matching by name.
  4. CultureInfo.InvariantCulture When this value changes CurrentCultureChanged is raised and all translatins updates and notifies.

Cultures.

Get a list with the available cultures. Cultures are found by looking in current directory and scanning for satellite assemblies.

ErrorHandling.

Get or set how errors are handled. The default value is ReturnErrorInfoPreserveNeutral.

Translate.

Translate a key in a ResourceManager.

Use global culture & error handling:

Translator.Culture = CultureInfo.GetCultureInfo("en"); // no need to set this every time, just for illustration purposes here.
string inEnglish = Translator.Translate(Properties.Resources.ResourceManager,
                                        nameof(Properties.Resources.SomeResource));

Translate to neutral culture:

string neutral = Translator.Translate(Properties.Resources.ResourceManager,
                                      nameof(Properties.Resources.SomeResource),
                                      CultureInfo.InvariantCulture);

Translate to explicit culture:

string inSwedish = Translator.Translate(Properties.Resources.ResourceManager,
                                        nameof(Properties.Resources.SomeResource),
                                        CultureInfo.GetCultureInfo("sv"));

Override global error handling (throw on error):

Translator.ErrorHandling = ErrorHandling.ReturnErrorInfo; // no need to set this every time, just for illustration purposes here.
string inSwedish = Translator.Translate(Properties.Resources.ResourceManager,
                                        nameof(Properties.Resources.SomeResource),
                                        ErrorHandling.Throw);

Override global error handling (return info about error):

Translator.ErrorHandling = ErrorHandling.Throw; // no need to set this every time, just for illustration purposes here.
string inSwedish = Translator.Translate(Properties.Resources.ResourceManager,
                                        nameof(Properties.Resources.SomeResource),
                                        ErrorHandling.ReturnErrorInfo);

Translate with parameter:

Translator.Culture = CultureInfo.GetCultureInfo("en");
string inSwedish = Translator.Translate(Properties.Resources.ResourceManager,
                                        nameof(Properties.Resources.SomeResource__0__),
                                        foo);

MissingTranslation.

An event that notifies when the key or culture is missing. Can be used for logging.

Translator.MissingTranslation += (sender, args) => Log($"Missing translation for {args.Key} when translating to {args.Language}.");

Translator<T>.

Same as translator but used like Translator<Properties.Resources>.Translate(...)

Translation.

An object with a Translated property that is a string with the value in Translator.CurrentCulture Implements INotifyPropertyChanged and notifies when for the property Translated if a change in Translator.CurrentCulture updates the translation.

GetOrCreate.

Returns an ITranslation from cache or creates and caches a new instance. If ErrorHandling is Throw it throws if the key is missing. If other than throw a StaticTranslation is returned.

Translation translation = Translation.GetOrCreate(Properties.Resources.ResourceManager, nameof(Properties.Resources.SomeResource))

StaticTranslation.

An implementation of ITranslation that never updates the Translatedproperty and returns the value of Translated when calling Translate()on it with any paramaters. This is returned from Translation.GetOrCreate(...) if the key is missing.

上一篇:
enyojs/g11n: Globalization + Localization library发布时间:2022-08-16
下一篇:
SpoonLabs/flacoco: Fault localization for Java based on Jacoco发布时间:2022-08-16
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap