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