在 WPF 中使用其他设置设置区域性

Set culture with additional settings in WPF

我正在尝试将我当前的区域性(具有自定义小数点符号)传递给 WPF,以便它将根据我在 windows 中的区域和语言设置显示绑定值。

我的研究总是以类似于 this 的解决方案结束,它传递语言标记,但不传递任何附加设置(如小数点符号)。

如何强制 WPF 使用整个当前区域性而不仅仅是默认语言设置?

关于可能的解决方法的问题:

我能否以某种方式将当前区域性传递给 WPF 使用的默认值转换器?或者覆盖它们?

有几个选项。也许最简单的方法是将要数据绑定的值包装到屏幕并为它们调用 ToString。例如,如果您有:

    public decimal Value
    {
        get { return this.value; }
        set
        {
            if (value == this.value) return;
            this.value = value;
            OnPropertyChanged();
        }
    }

像这样将它包裹在您的 ViewModel 中:

    public decimal Value
    {
        get { return this.value; }
        set
        {
            if (value == this.value) return;
            this.value = value;
            OnPropertyChanged("ValueString");
        }
    }

    public string ValueString
    {
        get { return this.value.ToString(CultureInfo.CurrentCulture); }
    }

并将你的 UI 绑定到这个新的 属性:

        <TextBlock x:Name="Result" Text="{Binding ValueString}" Grid.Row="0"/>

这样您将根据计算机的文化设置自动获取格式:

另一种方法是使用此处介绍的方法:

所以你需要一个自定义绑定class:

public class CultureAwareBinding : Binding
{
    public CultureAwareBinding(string path)
        : base(path)
    {
        ConverterCulture = CultureInfo.CurrentCulture;
    }
}

然后您必须在 XAML:

中使用它
        <TextBlock x:Name="Result" Text="{wpfApplication9:CultureAwareBinding Value}" Grid.Row="0"/>

之后您应该会看到所需的输出:

using System;
using System.Globalization;
using System.Threading;
using System.Windows;
using System.Windows.Markup;

namespace WPF_CultureExample
{
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("tr-TR");
            var currentCulture = Thread.CurrentThread.CurrentCulture.Name;
            var ci = new CultureInfo(currentCulture)
            {
                NumberFormat = { NumberDecimalSeparator = "," },
                DateTimeFormat = { DateSeparator = "." }
            };
            Thread.CurrentThread.CurrentCulture = ci;
            Thread.CurrentThread.CurrentUICulture = ci;

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

            base.OnStartup(e);
        }
        
    }
}

您可以在 App.xaml 文件的后端代码中重新编写 OnStartup() 方法。