c# - 为什么我不能在设计时在 XAML 中使用 CultureInfo.CurrentCulture?

标签 c# wpf xaml globalization

我有以下 XAML:

<TextBlock Text="{Binding Source={x:Static s:DateTime.Now}, StringFormat=Date: {0:dddd, MMMM dd}}"/>

s:DateTime.Now with xmlns:s="clr-namespace:System;assembly=mscorlib" 在运行时和设计模式(视觉Studio 2015 企业版)。

但是,如果我对 CultureInfo.CurrentCulture 进行同样的尝试,那么这仅在运行时有效,并且在设计模式中给我一个错误 (xmlns:c="clr-namespace:System.全局化;assembly=mscorlib"):

<TextBlock Text="{Binding Source={x:Static s:DateTime.Now}, ConverterCulture={x:Static c:CultureInfo.CurrentCulture}, StringFormat=Date: {0:dddd, MMMM dd}}"/>

我不是在寻找解决方法。我只是想了解 DateTime.NowCultureInfo.CurrentCulture 之间的区别,以及为什么其中一个有效而另一个无效。

最佳答案

我知道您没有要求解决方法,我无法回答您最初的问题。

我仍然想发布我的解决方案,以防其他人(例如我)在寻找解决方法时偶然发现您的问题。

如果您在 CustomBinding 类中设置您的 ConverterCulture 并在您的 xaml 中使用此 CustomBinding 而不是 Binding,它也可以在设计时工作。

public class CultureAwareBinding : System.Windows.Data.Binding
{
    public CultureAwareBinding()
    {
        ConverterCulture = CultureInfo.CurrentCulture;
    }
}

您可以像这样在您的 xaml 中使用它。

<TextBlock Text="{CultureAwareBinding Source={x:Static s:DateTime.Now}, StringFormat=Date: {0:dddd, MMMM dd}}"/>

作为一个额外的好处,这允许您稍后在需要时在一个地方更改 ConverterCulture。您也可以像这样设置其他属性,例如 StringFormat。

关于c# - 为什么我不能在设计时在 XAML 中使用 CultureInfo.CurrentCulture?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35129278/

相关文章:

html - HTML/CSS 中是否有等效的 XAML Grid 元素?

c# - wpf - 数据模板,使用按钮更改模板

c# - LINQ XML 查询 : How do I perform query for binding?

c# - 从模型中添加新项目计数

C#多形式编码实践

c# - 处理 Web API 返回的大型 JSON 数据

c# - 将 ViewModel 绑定(bind)到多个窗口

c# - 如何禁用 MVC 4 模型验证?

C#/WPF : Drag & Drop Images

.net - DisplayMemberPath 等属性成为依赖属性的原因/场景是什么?