在Silverlight中使用MVVM,在我的视图上我有:
<TextBox Text="{Binding Path=Temperature,Mode=TwoWay}" />
MyViewModel有:
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有:
private double _temperature;
public double Temperature
{
get
{
return _temperature;
}
set
{
_temperature = value; OnPropertyChanged("Temperature");
}
}
如果用户输入的内容不会解析为double,则Model.Temperature属性设置为0,我希望TextBox也更改为0.我认为OnPropertyChanged事件会处理这个问题。有什么想法发生了吗?
答案 0 :(得分:1)
编辑: 这是因为Text在调用set期间不会调用get。这可能会导致无限循环。你有几个选择。
错误条件的延迟触发属性已更改:
public string Temperature
{
get { return Model.Temperature.ToString(); }
set
{
double test;
if (double.TryParse(value, out test))
{
Model.Temperature = test;
}
else
{
Model.Temperature = 0D;
Deployment.Current.Dispatcher.BeginInvoke(() => OnPropertyChanged("Temperature"));
}
}
}
在ViewModel上实现IDataErrorInfo并将TextBox上的ValidatesOnDataErrors设置为true
<TextBox Text="{Binding Temperature, Mode=TwoWay, ValidatesOnDataErrors=True}"/>
OLD: 确保您的绑定允许two way binding。没有它,您无法设置TextBlock的TextProperty。
<TextBlock Text="{Binding Temperature, Mode=TwoWay}"/>