Thursday, September 13, 2012

How to change entered TextBox text in binded property setter?

How to change entered TextBox text in binded property setter?

Using MVVM in Silverlight, on my View I have:

<TextBox Text="{Binding Path=Temperature,Mode=TwoWay}" /> 

MyViewModel has:

public MyModel Model {get{...}set{...}}//In my code I do have the property changed events for this public string Temperature {     get     {         return Model.Temperature.ToString();     }     set     {         double test;         if(double.TryParse(value, out test))         {             Model.Temperature = test;         }         else         {             Model.Temperature = 0D;         }     } }  void Model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) {     switch(e.PropertyName)     {         case "Temperature":             OnPropertyChanged("Temperature");             break;     } } 

MyModel has:

private double _temperature; public double Temperature {     get     {         return _temperature;     }     set     {         _temperature = value; OnPropertyChanged("Temperature");     } } 

If the user enters something that would not parse to a double, the Model.Temperature property gets set to 0, and I would like the TextBox to also change to 0. I thought the OnPropertyChanged events would take care of that. Any ideas whats happening?

Answers & Comments...

Answer: 1

Make sure that your binding allow for two way binding. Without it, you cannot set the TextProperty of the TextBlock.

<TextBlock Text="{Binding Temperature, Mode=TwoWay}"/> 
by : Shawn Kendrothttp://stackoverflow.com/users/1054961




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog