【发布时间】:2019-11-13 10:34:53
【问题描述】:
目前我有一个自定义日期类,用于存储年份和年份:
public class CustomDate
{
public short Day { get; set; }
public short Year { get; set; }
public CustomDate(short day, short year)
{
this.Day = day;
this.Year = year;
}
}
这可以在类中使用:
public class Foo
{
public int Id { get; set; }
public CustomDate MyDate { get; set; }
}
到目前为止一切顺利。现在,如果想将此绑定到 winform datetimepicker 控件,我会执行以下操作:
private void BuildDob()
{
var bind = new Binding("Value", this._foo, "MyDate", true, DataSourceUpdateMode.OnPropertyChanged);
bind.Parse += (s, e) =>
{
e.Value = new CustomDate(
day: (short)((DateTime)e.Value).DayOfYear,
year: (short)((DateTime)e.Value).Year);
};
this.dtPickerDateOfBirth.DataBindings.Add(bind);
根据选择的日期被解析并正确设置在对象上,这可以正常工作。我面临的问题是 datetimepicker 在表单加载时没有显示/设置为正确的绑定日期,它设置为 01/01/1900,我猜这是因为我试图绑定到 CustomDate 哪个type 不能绑定到 datetimepicker。
我必须绑定到正确的属性但在加载时设置正确的日期的解决方案是什么?
【问题讨论】:
-
如果您为 DateTime 创建第二个属性,例如
public DateTime Date {get=> MyDate; set=> MyDate=value;}(在答案中使用隐式操作符)
标签: c# winforms data-binding datetimepicker