如何在DateTime类型的属性中将空白设置为默认值?

时间:2013-04-15 15:29:00

标签: c#

我创建了一个DateTime类型的属性。当我在InvokePropertyChanged()事件的标签中设置此属性值时,它显示默认值(1/1/0001 12:00:00)。如果属性没有有效日期,如何设置空白文本?

public event PropertyChangedEventHandler PropertyChanged;
private DateTime? _dDateTime = null;

public DateTime PostedDateTime
{
    get
    {
        return _dDateTime.HasValue ? _dDateTime.Value : DateTime.Now;
    }
    set
    {
        _dDateTime = value;
        InvokePropertyChanged(new PropertyChangedEventArgs("PostedDateTime"));
    }
}

public void InvokePropertyChanged(PropertyChangedEventArgs e)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, e);
        Refresh();
    }

    if (e.PropertyName.Equals("PostedDateTime"))
      lblDateTimeDt.Text = PostedDateTime.ToString();// setting datetime in label

}

1 个答案:

答案 0 :(得分:0)

您可以在分配

之前测试该值
public void InvokePropertyChanged(PropertyChangedEventArgs e)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
       handler(this, e);
       Refresh();
    }

    if (e.PropertyName.Equals("PostedDateTime"))
    lblDateTimeDt.Text = PostedDateTime == DateTime.MinValue ? "" : PostedDateTime.ToString();

}