在 DataGrid 中使用 WPF 格式化日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21021911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:28:06  来源:igfitidea点击:

Format date using WPF in DataGrid

c#wpfdatetime

提问by Andrew N

I have a DataGridthat has a Start Time column. This is bound to a string field which holds the time in the format hh:mm:ss. However, I want to only display the time in the grid in the format hh:mm. Is there a way of achieving this using the string format attribute in Binding.

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

回答by dovid

like this:

像这样:

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

回答by Andrew N

I've exhausted my search for trying to find out if there was a way for the StringFormat attribute of Binding in WPF to convert a string to a date and then format it as HH:mm.

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

So I've gone about creating a converter to do the same as suggested above. Thought I'd paste it here for use by anyone who has such a need.

所以我已经开始创建一个转换器来做与上面建议的相同的事情。我想我会把它贴在这里供有这种需要的任何人使用。

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;
    }
}

And here is how you achieve the result in WPF.

这是您如何在 WPF 中实现结果。

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

Lastly, don't forget to add the following, customised ofcourse to your needs.

最后,不要忘记添加以下定制课程以满足您的需求。

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

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

Hope this helps.

希望这可以帮助。