Muh*_*mar 2 data-binding validation wpf exception-handling exception
我想在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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的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>
Run Code Online (Sandbox Code Playgroud)
小智 6
我运行了你的代码,当在调试器下执行时,是的,VS调试器在抛出时停止,因为没有处理该异常的catch语句.
但是在没有调试的情况下启动时,应用程序不会崩溃 - 编辑框边框变为红色.
如果要删除异常,可以更改ViewModel以实现IDataErrorInfo接口,而不是抛出异常.
如果异常干扰了您的调试,您可以例如,开始抛出从ArgumentException或ValidationException派生的自定义异常,并且在抛出此自定义异常并且用户未处理时,配置VS不会中断