使用ValidatesOnExceptions在WPF中进行数据验证
我想使用使用ValidatesOnExceptions在WPF中进行数据验证,wpf,exception,data-binding,exception-handling,validation,Wpf,Exception,Data Binding,Exception Handling,Validation,我想使用ValidatesOnException在WPF中运行一个基本数据验证示例,但它根本不起作用,而且只要我的viewmodel抛出ValidationException,我的程序就会崩溃,说,ValidationException没有被用户代码处理 我的视图模型是 public class MainViewModel : INotifyPropertyChanged { //INotifyPropertyChaned implementation /////////////
ValidatesOnException
在WPF中运行一个基本数据验证示例,但它根本不起作用,而且只要我的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调试器会在抛出时停止,因为没有处理该异常的catch语句
但是在没有调试的情况下启动时,应用程序不会崩溃-编辑框边框变为红色
如果要消除异常,可以更改ViewModel以实现IDataErrorInfo接口,而不是引发异常
如果异常干扰了调试,例如,您可以开始抛出从ArgumentException或ValidationException派生的自定义异常,并将VS配置为在抛出此自定义异常且用户未处理时不中断,VS调试器在抛出时停止,因为没有处理该异常的catch语句。但是在没有调试的情况下启动时,应用程序不会崩溃-编辑框边框变为红色。如果要消除异常,可以将ViewModel更改为实现IDataErrorInfo接口,而不是抛出exception.aarghh!我花了3个小时在上面,相信我,我希望VS能够非常智能地处理这种验证,你能告诉我这是一种在Visual studio中不停止调试器的方法吗,目前我无法实现
IDataErrorInfo
,感谢@Jogy以任何方式提供的答案和建议,请写下你的评论作为这个问题的答案。谢谢,伙计。这对我帮助很大。