自定义DateTimePicker控件

时间:2011-08-10 07:58:53

标签: c# forms

我创建了实现DateTimePicker的用户控件。但我对Databindings有疑问。加载Control时,dtp.Value具有默认值DateTime。现在为值。为什么?

//Part of Form InitializeComponent() : 
this.dtp_user.DataBindings.Add(new System.Windows.Forms.Binding("Value",           this.employeesBindingSource, "BirthDate", true)); 

// Custom Control Contains two buttons and textBox (usrText)
public partial class usrDateTimePicker : UserControl
{

    private DateTimePicker dtp;

    private bool _cheked;
    public bool Checked
    { 
        get { return _cheked; }
        set { _cheked = value; }
    }

    public DateTime Value
    { 
        get { return dtp.Value; }
        set
        {
            if (value < DateTime.MinValue && value > DateTime.MaxValue)
                value = DateTime.Now;
            dtp.Value = value;
        }
    }

    public override string Text
    {
        get { return usrText.Text; }
    }

    public ControlBindingsCollection DataBindings
    {
        get { return dtp.DataBindings;}
    }

    usrCalendar clnd;
    Popup _popup;

    public usrDateTimePicker()
    {
        InitializeComponent();
        InitStyles();
        InitControls();
    }

    private void InitStyles()
    {
        //
    }

    private void InitControls()
    {
        dtp = new DateTimePicker();
        clnd = new usrCalendar();
        _popup = new Popup(clnd);
        _popup.Closed += popup_Closed;
    }
    protected override void OnLoad(EventArgs e)
    {
        usrText.Text = FormatDate(dtp.Value);
        base.OnLoad(e);
    }

    protected override void OnSizeChanged(EventArgs e)
    {
        //
    }

    private void btn_datetimepick_Click(object sender, EventArgs e)
    {
        if (!_popup.Visible)
        {
            _popup.Show(this);
        }
        else
            _popup.Close();
    }

    private void popup_Closed(object sender, ToolStripDropDownClosedEventArgs e)
    {
        dtp.Value = clnd.Value;
        usrText.Text = FormatDate(dtp.Value);
        _cheked = true;
        if (usrText.Text == string.Empty || usrText.Text == "")
            _cheked = false;
    }

    private string FormatDate(DateTime date)
    {
        // 
    }

1 个答案:

答案 0 :(得分:2)

默认情况下,DatePicker控件的Value设置为DateTime.Now,除非您专门设置了值。 Read Here