【问题标题】:DatePicker displays default date 1/1/0001 - C# WPFDatePicker 显示默认日期 1/1/0001 - C# WPF
【发布时间】:2017-07-26 00:45:27
【问题描述】:

我在 C# WPF 中使用日期选择器,它在 XAML 中定义为:

  <DatePicker  x:Name="TheDate"  Width="200" Text="{Binding ReportPlanningDate ,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}" IsTodayHighlighted="True" />

绑定属性ReportPlanningDate定义为:

public DateTime ReportPlanningDate
        {
            get { return _ReportPlanningDate; }
            set
            {
                if (_ReportPlanningDate == value) return;
                _ReportPlanningDate = value;
                PlanningDate = _ReportPlanningDate;
                OnPropertyChanged("ReportPlanningDate");
            }
        }
        public DateTime _ReportPlanningDate;
        public DateTime PlanningDate;

即使我将IsTodayHighlighted 设置为True,它也会显示1/1/0001。我在这里错过了什么?

【问题讨论】:

  • 如果你在set 中放置一个断点,它会在你的页面加载过程中被命中吗?如果是,value 的值是多少?
  • 它说:值 = {1/1/0001 12:00:00 AM} @Alexei
  • 然后,确保将其设置为当前日期。

标签: c# wpf datepicker


【解决方案1】:

IsTodayHighlighted 仅突出显示当前日期(如果您将日历滚动到当前日期,您会看到它被突出显示)但它不会选择它。 如果您有属性Text 绑定到 ViewModel 的属性,它是数据驱动的,因此它将根据数据选择日期。由于未设置数据,因此它具有默认值 (1.1.0001.)。
要解决这个问题,请指定默认值:

public DateTime _ReportPlanningDate = DateTime.Now;

【讨论】:

  • 您也可以在 ViewModel 的构造函数中将_ReportPlanningDate 设置为DateTime.Now.Date,您可以在其中编写更详细的逻辑。请注意,支持字段应该是私有的,而不是公共的
【解决方案2】:

IsTodayHighlighted 仅用于突出显示今天的日期。未设置默认日期。如果要设置默认日期,则需要设置SelectedDate 属性。

<my:DatePicker SelectedDate="{x:Static sys:DateTime.Now}"/>

如果需要,添加此引用。

xmlns:sys="clr-namespace:System;assembly=mscorlib"

正如link 中提到的那样。

【讨论】:

  • 但这是不是面向MVVM的,SelectedDate需要一个绑定
【解决方案3】:

将支持字段标记为私有

private DateTime _ReportPlanningDate; // only the property is public
//public DateTime PlanningDate; what's this?

可以在ViewModel的构造函数中设置

public class MyVM : ViewModelBase {
    public MvVM() {
        _ReportPlanningDate = DateTime.Now.Date;

你应该绑定日期选择器的选定日期

<DatePicker SelectedDate={Binding ReportPlanningDate}

【讨论】:

  • PlanningDate 在项目的其他地方。 thnx 关于“私人”的说明。
猜你喜欢
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多