我想知道是否可以将 datetimepicker 日期设置为 null
无法设置DateTimePicker.Value
为null
,因为它的类型不可为空。MSDN 说:
如果代码或用户未更改 Value 属性,则将其设置为当前日期和时间 (DateTime.Now)。
但这不是问题。您应该将某些绑定属性设置为空,而不是DateTimePicker.Value
:
public class MyModel : INotifyPropertyChanged
{
public DateTime? DateTimeFilter
{
get { return dateTimeFilter; }
set
{
if (dateTimeFilter != value)
{
dateTimeFilter = value;
OnPropertyChanged("DateTimeFilter");
}
}
}
private DateTime? dateTimeFilter;
// INotifyPropertyChanged implementation is omitted
}
public partial class Form1 : Form
{
private readonly MyModel model;
public Form1()
{
InitializeComponent();
model = new MyModel();
dateTimePicker1.DataBindings.Add("Value", model, "DateTimeFilter", true, DataSourceUpdateMode.OnPropertyChanged, DateTime.Now);
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(model.DateTimeFilter.HasValue ? string.Format("User has selected '{0}'.", model.DateTimeFilter) : "User hasn't selected anything.");
}
private void button2_Click(object sender, EventArgs e)
{
// here's the data binding magic: our model's property becomes null,
// and datetimepicker's value becomes DateTime.Now, as it was initially set
model.DateTimeFilter = null;
}
}