繁体   English   中英

WPF - 如何动态更改窗口的语言属性

[英]WPF - How to change language property of a window dynamically

我在应用程序中有一个用于购买产品的窗口。现在有两个选项本地或国外。如果用户点击本地货币,我的文本框的字符串格式持有利率和金额应该以欧元作为货币,如果用户选择外国应该是美元。

Window_Purchase.Language = ?

Window_Purchase 是我的窗口的名称。

如何在运行时更改语言属性。我不想仅更改货币格式的文本语言。提前致谢。

如果您有 2 个或更多资源文件,例如:
(它们需要在解决方案资源管理器中的Properties下添加)

资源.resx 在此处输入图片说明

资源.de.resx 在此处输入图片说明

它们可以通过实现INotifyPropertyChanged下面的类来动态切换。

namespace WpfApplication1.Properties
{
    using System.Globalization;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    using Properties;

    public class ResourceService : INotifyPropertyChanged
    {
        #region singleton members

        private static readonly ResourceService _current = new ResourceService();
        public static ResourceService Current
        {
            get { return _current; }
        }
        #endregion

        readonly Properties.Resources _resources = new Properties.Resources();

        public Properties.Resources Resources
        {
            get { return this._resources; }
        }

        #region INotifyPropertyChanged members

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = this.PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion

        public void ChangeCulture(string name)
        {
            Resources.Culture = CultureInfo.GetCultureInfo(name);
            this.RaisePropertyChanged("Resources");
        }
    }
}

并且您要更改的文本(货币)必须绑定它以接收这样的PropertyChanged事件:

<!-- Add xmlns:properties-->
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:properties="clr-namespace:WpfApplication1.Properties">

<TextBlock Text="{Binding Source={x:Static properties:ResourceService.Current}, Path=Resources.Currency, Mode=OneWay}"

然后,您可以动态更改CultureResources )。
例如:

private void Button_Click(object sender, RoutedEventArgs e)
{
    ResourceService.Current.ChangeCulture("de");
}

如果我猜对了,您不想更改应用程序上的文化信息吗?

Application.CurrentCulture = System.Globalization.GetCultureInfo("en-us");

https://msdn.microsoft.com/en-us/library/system.windows.forms.application.currentculture(v=vs.110).aspx

试试这个 instend 用于当前表单

System.Windows.FrameworkElement.LanguageProperty.OverrideMetadata(  
                typeof( System.Windows.FrameworkElement ),  
                new System.Windows.FrameworkPropertyMetadata(  
                    System.Windows.Markup.XmlLanguage.GetLanguage( System.Globalization.CultureInfo.CurrentCulture.IetfLanguageTag ) ) ); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM