Validation MVVM Light:这是验证和还原视图中的值的最佳方法吗?
在我看来,我有这样的文本框:Validation MVVM Light:这是验证和还原视图中的值的最佳方法吗?,validation,windows-phone-7,mvvm-light,revert,Validation,Windows Phone 7,Mvvm Light,Revert,在我看来,我有这样的文本框: <TextBox x:Name="tBoxShippingWeight" Text="{Binding ShippingWeight, Mode=TwoWay}" InputScope="Number" /> 当用户输入一个值时,我会进行基本验证(不是这个问题的重点),如果验证失败,我会使用System.Windows.MessageBox通知用户正确的参数,并将该值恢复到以前的值,该值始终有效,因为它来自默认的初始值或由用户正确输入。最后,我在执
<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);
}
}
公共字符串装运重量
{
获取{return ShippingModel.ShippingWeight.ToString();}
设置
{
if(ShippingModel.ShippingWeight.ToString()==值)返回;
var oldValue=ShippingModel.ShippingWeight;
尝试
{
int intValue=Convert.ToInt32(值);
if(Convert.ToInt32(ShippingParams.ShippingWeightMin)>intValue | | Convert.ToInt32(ShippingParams.ShippingWeightMax)
}/P>
可以考虑实施
调用BeginEdit时,使用一些专用字段存储旧值,并在验证失败或用户取消编辑时使用这些值。感谢您的格式修复!有趣!我一定会再看一看(只看了一眼)。我必须看看它如何与代码的其余部分交互。谢谢。仅供参考:DataGrid“知道”这个接口,并在可用时使用它。