【问题标题】:Format date using WPF in DataGrid [duplicate]在 DataGrid 中使用 WPF 格式化日期 [重复]
【发布时间】:2014-01-09 13:42:33
【问题描述】:

我有一个 DataGrid,它有一个 Start Time 列。这绑定到一个字符串字段,该字段以 hh:mm:ss 格式保存时间。但是,我只想以 hh:mm 格式在网格中显示时间。有没有办法使用绑定中的字符串格式属性来实现这一点。

【问题讨论】:

  • 真的是string field吗?如果是的话,你需要带有字符串操作的转换器。
  • 是的,它是字符串格式。我想知道 stringformat 是否有处理字符串数据类型的方法。还是谢谢。
  • 没有转换器,不可能。

标签: c# wpf datetime


【解决方案1】:

像这样:

<DataGridTextColumn Binding="{Binding MyDate, StringFormat='HH:mm'}" />

【讨论】:

  • 我认为如果数据是日期时间类型,这将起作用。我的是一个字符串。
【解决方案2】:

我已经用尽了我的努力,试图找出 WPF 中 Binding 的 StringFormat 属性是否有办法将字符串转换为日期,然后将其格式化为 HH:mm。

所以我已经着手创建一个转换器来执行与上述建议相同的操作。想把它贴在这里供有这种需要的人使用。

public class StringToDateConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
        {
            return string.Empty;
        }
        DateTime d;
        try
        {
            d = System.Convert.ToDateTime(value);
            return d;
            // The WPF code that uses this converter will then use the stringformat 
            // attribute in binding to display just HH:mm part of the date as required.
        }
        catch (Exception)
        {
            // If we're unable to convert the value, then best send the value as is to the UI.
            return value;
        }

    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //Insert your implementation here...
        return value;
    }
}

这是在 WPF 中实现结果的方法。

    <DataGridTextColumn Header="Start Time"  Width="Auto" Binding="{Binding VisitOpStartTime, Converter={StaticResource s2dConverter}, StringFormat=\{0:HH:mm\}}"></DataGridTextColumn>

最后,别忘了添加以下根据您的需求定制的课程。

    xmlns:converter="clr-namespace:[YourAppNamespace].Converters"

    <Window.Resources>
        <converter:StringToDateConverter x:Key="s2dConverter" />
    </Window.Resources>

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2018-03-21
    • 2022-06-22
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2017-02-19
    • 2013-01-19
    • 2011-07-17
    相关资源
    最近更新 更多