cubski cubski - 1 year ago 82 Question

Binding property to control in Winforms

What is the best way to bind a property to a control so that when the property value is changed, the control's bound property changes with it.

So if I have a property "FirstName" which I want to bind to a textbox "txtFirstName" text value. If I change FirstName to "Stack" the txtFirstName.Text also changes to "Stack".

I know this may sound a stupid question but I'll appreciate the help.


You must implement INotifyPropertyChanged And add binding to textbox.

I will provide C# code snippet. Hope it helps

class Sample : INotifyPropertyChanged
    private string firstName;
    public string FirstName
        get { return firstName; }
            firstName = value;
            InvokePropertyChanged(new PropertyChangedEventArgs("FirstName"));

    #region Implementation of INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    public void InvokePropertyChanged(PropertyChangedEventArgs e)
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, e);


Usage :

 Sample sourceObject = new Sample();
 sourceObject.FirstName = "Stack";