Binding a nullable datetime within WPF application

て烟熏妆下的殇ゞ 提交于 2020-12-06 04:17:11

问题


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

In XAML file :

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

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

  • How can I fix my code to display an empty string instead of 01/01/0001, for null values?

回答1:


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).

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

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



回答2:


The easiest way I've been found to handle nullable DateTime field using in a DatePicker is setting TargetNullValue=''

In XAML file:

<DatePicker Text={Binding dpc_date_engagement, Mode=TwoWay, TargetNullValue='', UpdateSourceTrigger=PropertyChanged} />


来源:https://stackoverflow.com/questions/28561190/binding-a-nullable-datetime-within-wpf-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!