Data bound custom control with updating data when changed
I have a question related to Data Binding
If we have class A with some property for example “UserName” and text control T1 bound as follow :
T1.DataBindings.Add("Text",A,"UserName",true,DataSourceUpdateMode.OnPropertyChanged);
I.e. property will be updated when user edit text
Now if instead of text box we have custom control C1 with control property “ControlProp” ( for example of type MyEnum ) and it is bound to class B with property MyProp of type MyEnum as following :
C1.DataBindings.Add("ControlProp ",B," MyProp",true,DataSourceUpdateMode.OnPropertyChanged);
The question开发者_开发知识库 is : how can be ensured behavior of custom control similar to text box described above , i.e. class B property will be updated when ControlProp changed ? Your help will be very valuable . Tnanks
First, your class B have to implement INotifyPropertyChanged interface. This is the complete code or class B
public class ClassB : System.ComponentModel.INotifyPropertyChanged
{
private string myprop;
public string MyProp
{
get
{
return myprop;
}
set
{
if (value != myprop)
{
myprop = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("MyProp"));
}
}
}
}
#region INotifyPropertyChanged Members
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
#endregion
}
Then, suposse that your custom control have a label inside, and you want to bind the text of the label with your instance of class B. For example:
public partial class MyCustomControl : UserControl
{
public MyCustomControl()
{
InitializeComponent();
}
public string MyCustomProperty
{
get
{
return label1.Text;
}
set
{
label1.Text = value;
}
}
}
If you bind the property MyProp of class B to MyCustomProperty of your custom control, when you change the property in your object, label1 should change its text.
ClassB objectB = new ClassB();
C1.DataBindings.Add("MyCustomProperty", objectB, "MyProp", true, DataSourceUpdateMode.OnPropertyChanged);
objectB.MyProp = "Text 1";
objectB.MyProp = "Text 2";
// The final text is Text2
I think I found the solution : Added Inotifypropertychange to the control definition : public partial class MyCustomControl : UserControl, INotifyPropertyChanged And in the controls property setter I raise the event ( as in Javier Morillo's example )
Thanks to all
精彩评论