【WPF】 本地化的最佳做法

这篇具有很好参考价值的文章主要介绍了【WPF】 本地化的最佳做法。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

  应用程序本地化有很多种方式,选择合适的才是最好的。这里只讨论一种方式,动态资源(DynamicResource) 这种方式可是在不重启应用程序的情况下进行资源的切换,不论是语言切换,还是更上层的主题切换。想要运行时切换不同的资源就必须使用 动态资源(DynamicResource) 这种方式。
图片是可以使用资源字典进行动态 binding 的 不要被误导了

资源文件

确保不同语言环境中资源 Key 是同一个,且对用的资源类型是相同的。
在资源比较多的情况下,可以通过格式化的命名方式来规避 Key 冲突。

资源文件的属性可以设置成:
生成操作:内容
复制到输出目录:如果较新则复制

上面的操作可以在不重新编译程序的情况下编辑语言资源并应用。

如果不想让别人更改语言资源则
生成操作:
复制到输出目录:不复制

英文资源文件 en-US.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">

    <sys:String x:Key="WindowsTitle">MainWindow</sys:String>
    <ImageSource x:Key="icon">pack://SiteOfOrigin:,,,/Icons/en-USicon.png</ImageSource>
    <sys:String x:Key="LanguageButton">LanguageButton</sys:String>

    <sys:String x:Key="LockTime-OneMinute">1 Minute</sys:String>
    <sys:String x:Key="LockTime-FiveMinute">5 Minute</sys:String>
    <sys:String x:Key="LockTime-TenMinute">10 Minute</sys:String>
    <sys:String x:Key="LockTime-FifteenMinute">15 Minute</sys:String>
    <sys:String x:Key="LockTime-ThirtyMinute">30 Minute</sys:String>
    <sys:String x:Key="LockTime-OneHour">1 Hour</sys:String>
    <sys:String x:Key="LockTime-TwoHour">2 Hour</sys:String>
    <sys:String x:Key="LockTime-ThreeHour">3 Hour</sys:String>
    <sys:String x:Key="LockTime-Never">Never</sys:String>
</ResourceDictionary>

中文资源文件 zh-CN.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">

    <sys:String x:Key="WindowsTitle">主窗口</sys:String>
    <ImageSource x:Key="icon">pack://SiteOfOrigin:,,,/Icons/zh-CNicon.png</ImageSource>
    <sys:String x:Key="LanguageButton">语言按钮</sys:String>

    <sys:String x:Key="LockTime-OneMinute">1 分钟</sys:String>
    <sys:String x:Key="LockTime-FiveMinute">5 分钟</sys:String>
    <sys:String x:Key="LockTime-TenMinute">10 分钟</sys:String>
    <sys:String x:Key="LockTime-FifteenMinute">15 分钟</sys:String>
    <sys:String x:Key="LockTime-ThirtyMinute">30 分钟</sys:String>
    <sys:String x:Key="LockTime-OneHour">1 小时</sys:String>
    <sys:String x:Key="LockTime-TwoHour">2 小时</sys:String>
    <sys:String x:Key="LockTime-ThreeHour">3 小时</sys:String>
    <sys:String x:Key="LockTime-Never">永不</sys:String>
</ResourceDictionary>

资源使用

App.xaml

设置默认语言资源,用于在设计阶段预览,并利用 VS 智能提示资源的 Key 防止 Key编写出错。

<Application
    x:Class="Localization.Core.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Localization.Core"
    StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/I18nResources/en-US.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

主界面布局

<Window
    x:Class="Localization.Core.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:local="clr-namespace:Localization.Core"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:operate="clr-namespace:Localization.Core.Operates"
    Title="{DynamicResource WindowsTitle}"
    Width="800"
    Height="450"
    Icon="{DynamicResource icon}"
    mc:Ignorable="d">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <ComboBox
            x:Name="comLan"
            Width="{Binding SizeToContent.Width}"
            Height="{Binding SizeToContent.Width}"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            SelectedValuePath="Tag"
            SelectionChanged="ComboBox_SelectionChanged">
            <ComboBoxItem Content="中文" Tag="zh-CN" />
            <ComboBoxItem Content="English" Tag="en-US" />
        </ComboBox>

        <StackPanel Grid.Row="1">

            <Button
                Margin="0,50,0,0"
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                Content="{DynamicResource LanguageButton}" />

            <ComboBox
                x:Name="cmTime"
                Width="120"
                Margin="20"
                VerticalAlignment="Center">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{operate:ResourceBinding Key}" />
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
        </StackPanel>

    </Grid>
</Window>

cs代码

public partial class MainWindow : Window
{
    ObservableCollection<KeyValuePair<string, int>>? TimeList { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        var lan = Thread.CurrentThread.CurrentCulture.Name;
        comLan.SelectedValue = lan;

        Loaded += MainWindow_Loaded;
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        TimeList = new ObservableCollection<KeyValuePair<string, int>>()
        {
            new KeyValuePair<string, int>("LockTime-OneMinute", 1),
            new KeyValuePair<string, int>("LockTime-FiveMinute", 5),
            new KeyValuePair<string, int>("LockTime-TenMinute", 10),
            new KeyValuePair<string, int>("LockTime-FifteenMinute", 15),
            new KeyValuePair<string, int>("LockTime-ThirtyMinute", 30),
            new KeyValuePair<string, int>("LockTime-OneHour", 60),
            new KeyValuePair<string, int>("LockTime-TwoHour", 120),
            new KeyValuePair<string, int>("LockTime-ThreeHour", 180),
            new KeyValuePair<string, int>("LockTime-Never", 0),
        };

        cmTime.ItemsSource = TimeList;
        cmTime.SelectedValue = TimeList[0];
    }

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.AddedItems is null) return;

        LanguageOperate.SetLanguage((e.AddedItems[0] as ComboBoxItem)!.Tag.ToString()!);
    }
}

App.config

language 配置项用于保存用户选择的语言类型

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<appSettings>
		<add key="language" value=""/>
	</appSettings>
</configuration>

辅助类

语言切换操作类

检查方法入参,有值则切换到指定的资源,无值则读取配置文件中的值,若配置文件中仍无值,则获取当前线程运行的语言环境,切换到与语言环境相匹配的资源,如果没有找到与之匹配的资源则不做操作。

切换资源之后,将配置文件中的 language 的 value 改为当前所选的语言保存并刷新配置文件,直到下次更改。

重写 Application 类的 OnStartup 方法,在 OnStartup 中调用 SetLanguage 方法以实现应用程序启动对语言环境的判别。

/// <summary>
/// 语言操作
/// </summary>
public class LanguageOperate
{
    private const string KEY_OF_LANGUAGE = "language";

    /// <summary>
    /// 语言本地化
    /// </summary>
    /// <param name="language">语言环境</param>
    public static void SetLanguage(string language = "")
    {
        if (string.IsNullOrWhiteSpace(language))
        {
            language = ConfigurationManager.AppSettings[KEY_OF_LANGUAGE]!;

            if (string.IsNullOrWhiteSpace(language))
                language = System.Globalization.CultureInfo.CurrentCulture.ToString();
        }

        string languagePath = $@"I18nResources\{language}.xaml";

        if (!System.IO.File.Exists(languagePath)) return;

        var lanRd = Application.LoadComponent(new Uri(languagePath, UriKind.RelativeOrAbsolute)) as ResourceDictionary;
        var old = Application.Current.Resources.MergedDictionaries.FirstOrDefault(o => o.Contains("WindowsTitle"));

        if (old != null)
            Application.Current.Resources.MergedDictionaries.Remove(old);

        Application.Current.Resources.MergedDictionaries.Add(lanRd);

        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[KEY_OF_LANGUAGE].Value = language;
        configuration.Save();
        ConfigurationManager.RefreshSection("AppSettings");

        var culture = new System.Globalization.CultureInfo(language);
        System.Globalization.CultureInfo.CurrentCulture = culture;
        System.Globalization.CultureInfo.CurrentUICulture = culture;
    }
}

资源 binding 解析类

ComBox 控件通常是通过 ItemSource 进行绑定,默认情况下是无法对绑定的资源进行翻译的。
通过继承 MarkupExtension 类 重写 ProvideValue 方法来实现,item 绑定 资源的 Key 的解析。

/// <summary>
/// markup extension to allow binding to resourceKey in general case
/// </summary>
public class ResourceBinding : MarkupExtension
{
    #region properties

    private static DependencyObject resourceBindingKey;
    public static DependencyObject ResourceBindingKey
    {
        get => resourceBindingKey;
        set => resourceBindingKey = value;
    }

    // Using a DependencyProperty as the backing store for ResourceBindingKeyHelper.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ResourceBindingKeyHelperProperty =
        DependencyProperty.RegisterAttached(nameof(ResourceBindingKey),
            typeof(object),
            typeof(ResourceBinding),
            new PropertyMetadata(null, ResourceKeyChanged));

    static void ResourceKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is FrameworkElement target) || !(e.NewValue is Tuple<object, DependencyProperty> newVal)) return;

        var dp = newVal.Item2;

        if (newVal.Item1 == null)
        {
            target.SetValue(dp, dp.GetMetadata(target).DefaultValue);
            return;
        }

        target.SetResourceReference(dp, newVal.Item1);
    }
    #endregion

    public ResourceBinding() { }

    public ResourceBinding(string path) => Path = new PropertyPath(path);

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if ((IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget)) == null) return null;

        if (((IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget))).TargetObject != null && ((IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget))).TargetObject.GetType().FullName is "System.Windows.SharedDp") return this;


        if (!(((IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget))).TargetObject is FrameworkElement targetObject) || !(((IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget))).TargetProperty is DependencyProperty targetProperty)) return null;

        #region binding
        Binding binding = new Binding
        {
            Path = Path,
            XPath = XPath,
            Mode = Mode,
            UpdateSourceTrigger = UpdateSourceTrigger,
            Converter = Converter,
            ConverterParameter = ConverterParameter,
            ConverterCulture = ConverterCulture,
            FallbackValue = FallbackValue
        };

        if (RelativeSource != null)
            binding.RelativeSource = RelativeSource;

        if (ElementName != null)
            binding.ElementName = ElementName;

        if (Source != null)
            binding.Source = Source;
        #endregion

        var multiBinding = new MultiBinding
        {
            Converter = HelperConverter.Current,
            ConverterParameter = targetProperty
        };

        multiBinding.Bindings.Add(binding);
        multiBinding.NotifyOnSourceUpdated = true;
        targetObject.SetBinding(ResourceBindingKeyHelperProperty, multiBinding);

        return null;
    }

    #region Binding Members
    /// <summary>
    /// The source path (for CLR bindings).
    /// </summary>
    public object Source { get; set; }
    /// <summary>
    /// The source path (for CLR bindings).
    /// </summary>
    public PropertyPath Path { get; set; }
    /// <summary>
    /// The XPath path (for XML bindings).
    /// </summary>
    [DefaultValue(null)]
    public string XPath { get; set; }
    /// <summary>
    /// Binding mode
    /// </summary>
    [DefaultValue(BindingMode.Default)]
    public BindingMode Mode { get; set; }
    /// <summary>
    /// Update type
    /// </summary>
    [DefaultValue(UpdateSourceTrigger.Default)]
    public UpdateSourceTrigger UpdateSourceTrigger { get; set; }
    /// <summary>
    /// The Converter to apply
    /// </summary>
    [DefaultValue(null)]
    public IValueConverter Converter { get; set; }
    /// <summary>
    /// The parameter to pass to converter.
    /// </summary>
    /// <value></value>
    [DefaultValue(null)]
    public object ConverterParameter { get; set; }
    /// <summary>
    /// Culture in which to evaluate the converter
    /// </summary>
    [DefaultValue(null)]
    [TypeConverter(typeof(System.Windows.CultureInfoIetfLanguageTagConverter))]
    public CultureInfo ConverterCulture { get; set; }
    /// <summary>
    /// Description of the object to use as the source, relative to the target element.
    /// </summary>
    [DefaultValue(null)]
    public RelativeSource RelativeSource { get; set; }
    /// <summary>
    /// Name of the element to use as the source
    /// </summary>
    [DefaultValue(null)]
    public string ElementName { get; set; }
    #endregion

    #region BindingBase Members
    /// <summary>
    /// Value to use when source cannot provide a value
    /// </summary>
    /// <remarks>
    /// Initialized to DependencyProperty.UnsetValue; if FallbackValue is not set, BindingExpression
    /// will return target property's default when Binding cannot get a real value.
    /// </remarks>
    public object FallbackValue { get; set; }
    #endregion

    #region Nested types
    private class HelperConverter : IMultiValueConverter
    {
        public static readonly HelperConverter Current = new HelperConverter();

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            return Tuple.Create(values[0], (DependencyProperty)parameter);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    #endregion
}

实现效果

wpf本地化,# WPF,wpf,本地化,多语言,microsoft文章来源地址https://www.toymoban.com/news/detail-656490.html

到了这里,关于【WPF】 本地化的最佳做法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Unity Localization】基础教程-带你入门Unity官方国际化本地化多语言插件Localization 单独修改配置文件即可一体化控制全局文本实现多语言转换

    Unity Localization 基础教程 随着经济全球化的趋势,游戏也逐渐变的不分国界。在进行游戏内文本的国际化本土化多语言切换时往往是需要制作组耗费大量精力,那么今天要学习的这款Unity官方推出的国际化本地化插件 Localization 就可以进行多语言文本的全局管理达到快速切换文

    2024年02月03日
    浏览(52)
  • 详解dedecms织梦远程图片本地化https链接图片无法本地化怎么解决

    最近有朋友遇到发布文章时候文章里面带https的站外图片无法本地化,以下是解决办法: 找到  dede//inc/inc_archives_functions.php文件里面GetCurContent($body)这个函数,里面 这一段改为: 第二步: 这一段改为: 搞定,这样发文章就可以把https的远程图片也本地化了 以上就是本文的全

    2024年02月02日
    浏览(32)
  • Remix本地化,加载本地合约文件,本地链接Remix

    智能合约IDE,在线的比较卡,而且切换网络面临文件丢失的风险,选择本地搭建Solidity本地编辑环境,Remix-IDE + Remixd组合,加载本地合约代码。这里用到两个工具: Remix IDE(本地IDE)+ Remixd (链接) Remix IDE 项目源码:https://github.com/ethereum/remix-project 介绍: Remix IDE是一个本地部署运

    2024年02月13日
    浏览(51)
  • Excalidraw本地化部署

    1 - Excalidraw介绍 Excalidraw是一个开源、小巧易用的手写风格的框图画板软件。 ​excalidraw官网地址:https://excalidraw.com/​ 2 - Excalidraw本地化安装(git方式) 2-1安装部署 在terminal中,输入: 安装完成后,在terminal中,进入项目文件 2-2 安装依赖环境 - nodeJS NodeJS下载地址: nodejs下载

    2024年02月14日
    浏览(43)
  • 本地化GPT:LangChain + ChatGLM == 知识本地库

    OpenAI发布的ChatGPT Plugin刚刚杀死了一个创业公司LangChain(刚获得1000万美金种子轮融资) 由于语言模型的输出是通过自回归+采样[可选]完成的,在高精度场景下,即使是超大语言模型,发生错误概率也是指数级的。同时,采样也很容易引入错误。比如地址中的数字门牌号,模型

    2024年02月11日
    浏览(41)
  • Remix 完全本地化部署

    1.简介 Remix 是我们开发 Solidity 智能合约的常用工具,有时候我们会直接访问在线版的 Remix-IDE。 https://remix.ethereum.org/ 但是,如何将在线Remix链接本地文件系统呢,下面则是部署步骤 2、部署 Remixd Remixd 的安装使用步骤如下: 安装 Remixd:  npm install -g @remix-project/remixd 启动 Rem

    2024年02月17日
    浏览(42)
  • hadoop本地化windows部署

    需求背景是java代码提交服务器测试周期流程太慢,需要一种能直接在windows本地部署的相关组件。分析项目现有大数据技术栈,包括hadoop、hive和spark(sparksql),存储和计算都依赖windows系统。期中hive保存在本地的hadoop上,spark提交在hadoop的yarn上。 · hadoop on windows · hive on windows

    2024年02月16日
    浏览(66)
  • 本地化部署stable diffusion

    本文是根据https://zhuanlan.zhihu.com/p/606825889 和 https://blog.csdn.net/cycyc123/article/details/129165844两个教程进行的部署测试,终端是windows 前期需要安装python与git环境,这里不赘叙了,首先是几个下载包,可以提前下载: stable diffusion的web界面环境 https://pan.xunlei.com/s/VNQ4LqoKBidPdqSj2xMioVhs

    2023年04月09日
    浏览(60)
  • 本地化部署大语言模型 ChatGLM

    ChatGLM-6B 是一个开源的、支持中英双语的对话语言模型,基于 General Language Model (GLM) 架构,具有 62 亿参数。结合模型量化技术,用户可以在消费级的显卡上进行本地部署(INT4 量化级别下最低只需 6GB 显存)。 ChatGLM-6B 使用了和 ChatGPT 相似的技术,针对中文问答和对话进行了优

    2023年04月20日
    浏览(59)
  • Unity官方本地化插件localization

    官方文档地址:https://docs.unity3d.com/Packages/com.unity.localization@1.0/manual/QuickStartGuideWithVariants.html PackageManager搜索Localization完成对应插件的安装   PlayerSetting-Localization 创建本地化相关配置   创建之后点击Locale Generator可以选择需要支持的语言   TableCollection是一组本地化数据的集合

    2024年02月08日
    浏览(76)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包