【发布时间】:2012-09-03 03:56:03
【问题描述】:
我想在 WPF 中使用 ValidatesOnException 运行一个基本数据验证示例,但它根本不起作用,并且一旦我的 viewmodel 抛出 ValidationException,我的程序崩溃说,ValidationException 未被处理用户代码。
我的视图模型是
public class MainViewModel : INotifyPropertyChanged
{
//INotifyPropertyChaned implementation
//////////////////////////////////////
private string stringValue;
public string StringValue
{
get { return stringValue; }
set
{
if (value.Length > 6)
{
//The below line throws unhandled exception error??
throw new ValidationException(String.Format("Value's length is greater than {0}.", value.Length));
}
stringValue = value;
this.OnPropertyChanged("StringValue");
}
}
}
我的 XAML 是
<StackPanel x:Name="LayoutRoot" Background="White">
<TextBox x:Name="radMaskedTextInput1"
Width="200"
Margin="10"
Text="{Binding Path=StringValue, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
【问题讨论】:
-
我运行了你的代码,当在调试器下执行时,是的,VS 调试器在 throw 处停止,因为没有处理该异常的 catch 语句。但是在没有调试的情况下启动时,应用程序不会崩溃 - 编辑框边框变为红色。如果你想摆脱异常,你可以改变 ViewModel 来实现 IDataErrorInfo 接口而不是抛出异常。
-
啊!我花了 3 个小时在上面,相信我希望 VS 能够非常聪明地处理这种验证,你能告诉我这是不是在不停止调试器的情况下使用 Visual Studio 的任何方法,目前我可以' t 实施
IDataErrorInfo,感谢@Jogy 以任何方式回答和建议,请写下您的 cmets 作为此问题的答案。
标签: wpf exception data-binding exception-handling validation