views:

163

answers:

1

Hello.

I have a TextBox in my WPF window.

I have a property in the code behind called Text as well.

I want the text property to be bound to the Text property (i.e. when the value changes in the property the textbox value should also be updadated.

Thanks

+1  A: 

You have to set the DataContext of the TextBox control (or of any of its parents) to your window:

myTextBox.DataContext = this;

then in your XAML:

<TextBox Text={Binding Text} x:Name="myTextBox"/>
Mart
Does that property has to be a DependencyProperty?
Shimmy
Depending on the declaration of your Text property (which should be a DependencyProperty), you may have to explicitly set a TwoWay binding: {Binding Text, Mode=TwoWay}
Mart
It can be a DependencyProperty (use the propdp code snippet in Visual Studio) or the object can implement the INotifyPropertyChanged interface.
Mart
I actually don't need it as a two way, i only want that when the Window.Text is changed the TextBox.Text should be updated.
Shimmy
@Mart, can you be more specific, I think I like what you say
Shimmy
If you define your Window.Text as a DependencyProperty, the TextBox.Text will be updated automatically. Example of a DP definition:public string Text{ get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); }}public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(Window), new UIPropertyMetadata(string.Empty));
Mart
Thanks for your effort and sorry for not telling you my exact question. I meant how could I do this using the INotifyPropertyChanged tha you said above.
Shimmy
The INotifyPropertyChanged interface is used when you want to bind a whole object rather than a single dependency property. Basically each of your object's property raises a PropertyChanged event in its setter. This way WPF knows the value has changed and reflects it to the user interface.
Mart
I think this is what I am looking for, what message do I have to call at the property (a regular property, right?)?
Shimmy
Each time a (regular) property value is changed, a PropertyChanged event is raised. Example:public event PropertyChangedEventHandler PropertyChanged;protected void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); }private string _text;public string Text { get { return _text; } set { if (_text != value) { _text = value; OnPropertyChanged("Text"); } } }
Mart
But I am using it in a window where the OnPropertyChanged method is already implemented asking me to pass DependencyPropertryChangedEventArgs as a param?
Shimmy
As I told you, if your property is attached to the window, you should have a DependencyProperty as described before. The INotifyPropertyChanged technique is used when you bind to a custom class.
Mart
Thanks for all your help!
Shimmy