如何将DateTime的默认值设置为空字符串?

3
我有一个名为Raised_Time的属性,该属性显示在datagrid单元格中触发告警的时间。当用户创建任何告警时,我不想在datagrid单元格中显示任何内容,它只显示空单元格。
我在互联网上搜索并发现可以使用DateTime.MinValue设置DateTime的默认值,并且这将显示datetime的MinValue,即“1/1/0001 12:00:00 AM”。
相反,我希望datagrid单元格保持空白,直到触发告警,它不显示任何时间。
我认为可以针对此情况编写datatrigger。但是我无法为此场景编写datatrigger。我是否还需要编写一个转换器来检查DateTime是否设置为DateTime.MinValue以使datagrid单元格保持空白?
请帮忙!

3
在互联网上进行谷歌搜索.. 很不错 ;) - Arcturus
4个回答

9

我会使用转换器来完成这个任务,因为我可以很容易地看到未来会重复使用它。这是一个我曾经使用过的转换器,它将DateFormat的字符串值作为ConverterParameter。

public class DateTimeFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if ((DateTime)value == DateTime.MinValue)
            return string.Empty;
        else
            return ((DateTime)value).ToString((string)parameter);
    }


    public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture)
    {
        throw new System.NotImplementedException();
    }
}

7
我看到两个简单的解决方案:
  1. 您可以使用可空数据类型DateTime?,这样如果未设置警报时间,您就可以存储null而不是DateTime.MinValue

  2. 您可以使用一个转换器,这里有一个例子


3
那么直接将属性改为指向一个私有的DateTime字段如何?例如:
public string Raised_Time
{
  get
  {
    if(fieldRaisedTime == DateTime.MinValue)
    {
      return string.Empty();
    }
    return DateTime.ToString();
  }
  set
  {
    fieldRaisedTime = DateTime.Parse(value,   System.Globalization.CultureInfo.InvariantCulture);
  }
}

2
我为此使用了一个可空的日期时间nullable datetime,并使用以下扩展方法:
 public static string ToStringOrEmpty(this DateTime? dt, string format)
 {
     if (dt == null)
        return string.Empty;

     return dt.Value.ToString(format);
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接