【问题标题】:DisplayFormat with CultureInfo DateTime带有 CultureInfo 日期时间的 DisplayFormat
【发布时间】:2012-07-19 13:59:57
【问题描述】:

我正在尝试将公共属性的 DisplayFormat 设置为当前的文化信息日期时间格式。该类将用于 Silverlight Datagrid。

    [DisplayFormat(DataFormatString=CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString())]
    public DateTime createDate { get; set; }

它说,只有参数只能是常量和typeof参数......

有什么想法吗?

更新,我尝试了 Lukazoid 解决方案,但 Silverlight 数据网格忽略了数据注释。由于本地化,数据网格列被添加到代码隐藏中。

该列如下所示:

        DataGridTextColumn tcCreateDate = new DataGridTextColumn();
        tcCreateDate.Header = SilverlightApplication.Resources.ContentGrid.dgCreateDate;
        tcCreateDate.Binding = new Binding("createDate");

【问题讨论】:

    标签: c# localization data-annotations


    【解决方案1】:

    属性值必须是常量或typeof 语法的结果。

    如果要对当前文化使用短日期格式,请使用以下格式字符串:

    [DisplayFormat(DataFormatString = "{0:d}")]
    

    更新

    我可以看到你的更新代码添加DataGridTextColumn,试试这个添加StringFormat

    DataGridTextColumn tcCreateDate = new DataGridTextColumn();
    tcCreateDate.Header = SilverlightApplication.Resources.ContentGrid.dgCreateDate;
    tcCreateDate.Binding = new Binding("createDate") { StringFormat = "{0:d}" };
    

    默认情况下,silverlight 使用 en-US 作为所有绑定的当前区域性(无论您的系统设置如何),这意味着 StringFormat 将生成美国格式的日期。请参阅here 以获取确保您当前设置得到考虑的解决方案。

    【讨论】:

    • 嗯,它不像我想的那样工作。我在silverlight 的数据网格中使用该类。我是否也必须设置数据网格列的显示格式?
    • silverlight datagrid 似乎忽略了这个属性,所以我会使用 datagrid 列中的格式字符串(我也觉得优先在 UI 中设置 UI 格式而不是隐藏在代码中)
    • 对于本地化,我在代码隐藏而不是 xaml 中添加数据网格列。你知道如何添加这个字符串吗?查看我更新的帖子。
    • 我已经更新了我的答案,让我知道这是否符合您的要求。
    • 感谢您的更新。现在我得到一个日期格式 07/20/2012。但目前的文化是德国,我们的格式是 20.07.2012。
    【解决方案2】:

    这样尝试过

    public class Foo
    {
        [DataType(DataType.DateTime)]
        public DateTime createDate { get; set; }
    }
    

    这将显示您项目的日期基础文化

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 1970-01-01
      • 2019-11-19
      相关资源
      最近更新 更多