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?
EDIT:
This is caused because the Text will not call the get during the call to set. This could cause a bad infinite loop. You have a few choices.
Delay firing property changed for the error condition:
Use a NumericTextBox
Implement IDataErrorInfo on your ViewModel and set ValidatesOnDataErrors on your TextBox to true
OLD:
Make sure that your binding allow for two way binding. Without it, you cannot set the TextProperty of the TextBlock.