1

在 App.xaml.cs 我有:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

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

在我的 MainWindow.xaml.cs 我有:

NumberFormatInfo nfi = System.Threading.Thread.CurrentThread
                       .CurrentCulture.NumberFormat;
nfi.CurrencySymbol = "USD";
nfi.CurrencyDecimalSeparator = ".";
nfi.CurrencyDecimalDigits = 0;

NumberFormatInfo nfi = System.Threading.Thread.CurrentThread
                       .CurrentUICulture.NumberFormat;
nfi.CurrencySymbol = "USD";
nfi.CurrencyDecimalSeparator = ".";
nfi.CurrencyDecimalDigits = 0;

现在在另一个将从 MainWindow 打开的窗口中,我写了以下内容:

<TextBox Text="{Binding Total, StringFormat=c}"

但结果是 1,200.00 美元,而不是我的预期:1,200 美元。这里有什么问题?

4

2 回答 2

1

可能有更聪明的方法,但这应该始终如一地工作......

// xmlns:sysglb="clr-namespace:System.Globalization;assembly=mscorlib"
<TextBox Text="{Binding Total, StringFormat='{}{0:C}', ConverterCulture={x:Static sysglb:CultureInfo.CurrentUICulture}}" />  

并在应用程序启动或 ctor 时移动它...

然后做OverrideMetadata和之前base.OnStartup- 例如..

protected override void OnStartup(StartupEventArgs e)
{
    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");

    NumberFormatInfo nfi = System.Threading.Thread.CurrentThread
                            .CurrentCulture.NumberFormat;
    nfi.CurrencySymbol = "USD";
    nfi.CurrencyDecimalSeparator = ".";
    nfi.CurrencyDecimalDigits = 0;

    nfi = System.Threading.Thread.CurrentThread
                            .CurrentUICulture.NumberFormat;
    nfi.CurrencySymbol = "USD";
    nfi.CurrencyDecimalSeparator = ".";
    nfi.CurrencyDecimalDigits = 0;

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

    base.OnStartup(e);

}

也可以看看:

WPF StringFormat={0:C} 显示为美元

于 2013-04-11T12:17:11.990 回答
0

NumberFormatting 是使用您的 CurrentCulture 的操作(默认情况下,除非您明确地向该方法提供 Culture 或 NumberFormatter)而不是 CurrentUICulture。CurrentUICulture 用于资源(本地化)查找。

您从 CurrentCulture 获得的 NumberFormatInfo 应该是只读的(请参阅 NumberFormatInfo 文档的备注),并且在您尝试设置任何属性时应该抛出 InvalidOperationException (请参阅 NumberFormatinfo.IsReadOnly 的备注)。(您是否正在接受此异常?)如果您创建一个可写的 CultureInfo 并更改其属性,则可以将其设置为您当前的文化。

您需要执行以下操作:

CultureInfo ci = CultureInfo.CreateSpecificCulture("en-US");
NumberFormatInfo nfi= ci.NumberFormat;
nfi.CurrencySymbol = "USD";
nfi.CurrencyDecimalSeparator = ".";
nfi.CurrencyDecimalDigits = 0;
// set the default culture for all threads that haven't been explicitly set (.Net 4.5)
CultureInfo.DefaultThreadCurrentCulture = ci;
// or the following if you aren't using .Net 4.5
// Thread.CurrentThread.CurrentCulture = ci;
于 2013-04-11T19:45:21.850 回答