本文介绍了在WPF应用程序中绑定可为null的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个wpf应用程序,其中有此属性可绑定到 datepicker

I have a wpf application in which I had this property to bind to a datepicker

public Nullable<System.DateTime> dpc_date_engagement { get; set; }

所以我添加了一个转换器:

So I add a converter :

 public class DateConverter : IValueConverter
   {
       public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null)
            return ((DateTime)value).ToShortDateString();
        return String.Empty;
    }

       public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
       {
           string strValue = value.ToString();
           DateTime resultDateTime;
           return DateTime.TryParse(strValue, out resultDateTime) ? resultDateTime : value;
       }
   }

在XAML文件中:

                     <DatePicker >
                                <DatePicker.Text>
                                    <Binding Path="dpc_date_engagement" UpdateSourceTrigger="PropertyChanged">
                                        <Binding.Converter>
                                            <converter:DateConverter/>
                                        </Binding.Converter>
                                    </Binding>
                                </DatePicker.Text>
                            </DatePicker>

问题是当日期为空时,显示的文本为1/1/0001.

The problem is when the date is null, the displayed text is 1/1/0001.

  • 如何修复代码以显示空字符串(而不是01/01/0001)以表示空值?

推荐答案

传递给转换器的Nullable value 本身不是 null ,即使它包含> null 值(它甚至不能为null,因为它是一个结构,因此不能为空).

The Nullable value passed to your converter is not itself null, even if it holds a null value (it can't even be null, because it is a struct and therefore not nullable).

因此,您不必将 value null 进行比较,而必须将其强制转换为 Nullable< Datetime> ,然后检查其 HasValue 属性.

So instead of comparing value to null, you'll have to cast it to Nullable<Datetime> and then check its HasValue property.

此外,绑定属性中似乎有类似 DateTime.MinValue 的东西,而不是 null .因此,您也应该对此进行检查:

Moreover, you seem to have something like DateTime.MinValue in your bound property instead of null. So you should check against that, too:

public object Convert(...)
{
    var nullable = (Nullable<DateTime>)value;

    if (nullable.HasValue && nullable.Value > DateTime.MinValue)
    {
        return nullable.Value.ToShortDateString();
    }

    return String.Empty;
}

这篇关于在WPF应用程序中绑定可为null的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 20:45