在我看来,我有这样的文本框:
<TextBox x:Name="tBoxShippingWeight" Text="{Binding ShippingWeight, Mode=TwoWay}" InputScope="Number" />
当用户输入一个值时,我会进行基本验证(不是这个问题的重点),如果失败,我会使用 System.Windows.MessageBox 通知用户正确的参数并将值恢复为以前的值,这总是有效的,因为它要么来自默认的初始值,要么由用户正确输入。我最终在执行验证的 if 语句中调用了 RaisePropertyChanged("ShippingWeight") 。如果我把它放在 catch 语句中,如果 MessageBox 也从那里被调用,它就永远不会被引发。这是进行还原的合理方法还是有更好的方法?这是来自 ViewModel 的代码:
public string ShippingWeight
{
get { return ShippingModel.ShippingWeight.ToString(); }
set
{
if (ShippingModel.ShippingWeight.ToString() == value) return;
var oldValue = ShippingModel.ShippingWeight;
try
{
int intValue = Convert.ToInt32(value);
if (Convert.ToInt32(ShippingParams.ShippingWeightMin) > intValue || Convert.ToInt32(ShippingParams.ShippingWeightMax) < intValue)
{
// Revert back to previous value
// NOTE: This has to be done here. If done in the catch statement,
// it will never run since the MessageBox interferes with it.
RaisePropertyChanged("ShippingWeight");
throw new Exception();
}
ShippingModel.ShippingWeight = intValue;
RaisePropertyChanged("ShippingWeight", oldValue, Convert.ToDouble(value), true);
}
catch (Exception)
{
System.Windows.MessageBox.Show("Value must be a whole number between " + ShippingParams.ShippingWeightMin + " and " + ShippingParams.ShippingWeightMax);
}
}
}