【问题标题】:Datetimepicker Databinding custom typeDatetimepicker 数据绑定自定义类型
【发布时间】: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


【解决方案1】:

我相信您可以创建一个隐式运算符来将您的 CustomDate 类型转换为 DateTime,反之亦然:

public class CustomDate
{
    public int Day { get; set; }

    public int Year { get; set; }

    public CustomDate(int day, int year)
    {
        this.Day = day;
        this.Year = year;
    }

    public override string ToString()
    {
        return Year + "/" + Day;
    }

    public static implicit operator CustomDate(DateTime _dt) => new CustomDate(_dt.DayOfYear, _dt.Year);
    public static implicit operator DateTime(CustomDate _dt) => new DateTime(_dt.Year,1,1).AddDays(_dt.Day-1);


}

Day 和 Year 属性是整数而不是短裤,我不明白为什么要更改它...

https://dotnetfiddle.net/wa9eji

【讨论】:

  • 我明白你在做什么,但这不会影响绑定:this.dtPickerDateOfBirth.DataBindings.Add("Value", this._foo, "MyDate", true, DataSourceUpdateMode.OnPropertyChanged );当控件加载时,它仍然是 01/01/1900,无论如何
  • 对不起,我将删除答案...您可以自定义 DateTimePicker 控件吗?
猜你喜欢
  • 2012-12-14
  • 1970-01-01
  • 2018-03-09
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 2011-12-13
  • 2010-12-22
相关资源
最近更新 更多