In WinForms with C# 4.0 / C# 2.0, I cannot bind to a control if the control's visible field is false:
this.checkBox_WorkDone.DataBindings.Add("Visible", WorkStatus, "Done");
I can confirm the binding is successfully added to the control's databindings list but if I change my bound object (WorkStatus), nothing happens.
This is what WorkStatus looks like:
public class WorkStatus : INotifyPropertyChanged
{
private Boolean _done;
public Boolean Done
{
get { return _done; }
set
{
if (_done == value) return;
_done = value;
// fire event
RaisePropertyChanged("Done");
}
}
private Int32 _time;
public Int32 Time
{
get { return _time; }
set
{
if (_time == value) return;
_time = value;
// fire event
RaisePropertyChanged("Time");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(String propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null) { PropertyChanged(this, e); }
}
}
Edit
To reproduce, just set the Visible=false in the designer, or in the constructor before the databinding.
Using one overload of the Add() method fails too:
this.checkBox_WorkDone.DataBindings.Add("Visible", WorkStatus, "Done",
true, DataSourceUpdateMode.OnPropertyChanged);
The reason I want to hide the control is that I don't want user to see the control when the form is shown the very first time.
Solution
Thanks guys, I think I find a solution for this:
just set the Control.Visible = false in the Form.Load() event. In that case the control is not visible when the form is shown.
Although, why MS design the data binding in this way is still unknown.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…