DatePicker数据绑定将默认值设置为1/1/0001 WPF c#

Eri*_*ika 3 c# data-binding wpf datetime datepicker

我有一个DatePicker绑定到一个对象内的DataTime,并在运行时,而不是DatePicker中的字符串"选择一个日期",显示"1/1/0001",使得很难使用实际的日历.当我使用字符串绑定DatePicker时,我没有遇到任何问题,但将其更改为DateTime就是这样做的.请让我知道这是如何工作的.这是我到目前为止:

在XAML中我有:

<DatePicker Grid.Column="4" Grid.Row="9" Name="dueDateBox" VerticalAlignment="Center">
    <DatePicker.SelectedDate>
        <Binding Path="DueDate" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
            <Binding.ValidationRules>
                <my:DateRangeRule/>
            </Binding.ValidationRules>
        </Binding>
    </DatePicker.SelectedDate>
</DatePicker>
Run Code Online (Sandbox Code Playgroud)

在C#我有:

public DateTime DueDate
{
    get { return dueDate; }
    set
    {
        if (DueDate != null) || !DueDate.Equals(value))
        {
            dueDate = value;
            OnPropertyChanged("DueDate");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我也有一个依赖属性集,不确定这是否正在发挥作用:

public static readonly DependencyProperty DueDateProperty =
        DependencyProperty.Register("DueDate", typeof(DateTime),
        typeof(UpdateJobDialog), new PropertyMetadata(DateTime.Now));
Run Code Online (Sandbox Code Playgroud)

Kev*_*lia 6

可能有助于使用DateTime?而不是DateTime,因为DateTime不可为空,您将设置为默认值1/1/0001,而不是null,这将导致请选择您习惯的日期消息.

public DateTime? DueDate
{
    //Need to change the type of the private variable as well
    get { return dueDate; }
    set
    {
        if (DueDate != null) || !DueDate.Equals(value))
        {
            dueDate = value;
            OnPropertyChanged("DueDate");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)