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

标签 c# wpf datetime data-binding datepicker

我有一个 DatePicker 绑定(bind)到一个对象内的 DataTime,在运行时,DatePicker 中显示的不是字符串“Select a Date”,而是“1/1/0001”,因此很难使用实际日历.当我将 DatePicker 与字符串绑定(bind)时我没有遇到问题,但是将它更改为 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>

在 C# 中我有:

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

我还有一个依赖属性集,不确定这是否起作用:

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

最佳答案

可能有助于使用 DateTime?而不是 DateTime,因为 DateTime 不可为 null,您将设置为默认值 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");
        }
    }
}

关于c# - DatePicker 数据绑定(bind)将默认值设置为 1/1/0001 WPF c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11146977/

相关文章:

c# - c# - 如何检查另一个文件中的文件内容?

c# - 移出表单时更改 DragEffect

WPF/银光 : How do I create a BehaviorCollection on a control that doesn't already have one?

ios - 如何在iOS上将日期与时区进行比较

MySQL datetime 默认时间间隔

c# - 获取文本文件并随应用程序一起提供

c# - JObject 与 ExpandoObject

wpf 树状 View mvvm

.net - WPF 动画/UI 功能性能和基准测试

php - 使用 PHP 的 DateTime 类验证有效日期