bushmobile
bushmobile

Reputation: 13

Two way data binding to a control under a property

I have a custom class in which I've implemented INotifyPropertyChanged and I can happily bind this to the .Text property of a TextBox on a form and have the data flow both ways.

I'm now trying to achieve the same thing with a textbox on a usercontrol, via a property:

public string MyProperty
{
    get { return MyPropertyTextBox.Text; }
    set { MyPropertyTextBox.Text = value; }
}

I can bind my class to the MyProperty on the Usercontrol so that the value is set.

But how do I get it so that when I edit the textbox the change is fed back to my class?

Edit:

Not sure I explained myself very well + it's WinForms, not WPF.

The text box itself isn't bound, I wanted the 'TextChanged' event of the textbox to also trigger 'PropertyChanged' of the usercontrol property. Built myself a proof of concept test, got that working, and then managed to implement it in my project.

thanks for the suggestions though.

Upvotes: 1

Views: 1191

Answers (3)

crthompson
crthompson

Reputation: 15865

Add the OnPropertyChanged method to your property. Something like this:

private string _myPropertyText;
public string MyProperty
{       
    get { return _myPropertyText; }
    set { 
         if(_myPropertyText != value) 
         {
            _myPropertyText = value; 
            OnPropertyChanged("MyPropertyTextBox");
         }
        }
}

You didn't mention XAML in your question, but as @RetailCoder has noted, your XAML needs to be set properly as well, like in Alan's answer.

<TextBox Text="{Binding myProperty,UpdateSourceTrigger=PropertyChanged}" 

Upvotes: 3

Alan
Alan

Reputation: 171

If you want it to update while editing, use this xaml

<TextBox Text="{Binding myproperty,UpdateSourceTrigger=PropertyChanged}" 

Upvotes: 1

sino
sino

Reputation: 776

while you are directly ready from textbox.Text , any change will be directly detected no need for extra code

Upvotes: -2

Related Questions