gpt4 book ai didi

wpf - WPF 中使用 ValidatesOnExceptions 进行数据验证

转载 作者:行者123 更新时间:2023-12-02 02:13:16 26 4
gpt4 key购买 nike

我想使用 ValidatesOnException 在 WPF 中运行基本数据验证示例,但它根本不起作用,并且一旦我的 viewmodel 抛出 ValidationException,我的程序崩溃并提示:ValidationException 未由用户代码处理

我的 View 模型是

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接口(interface),而不是抛出异常。

如果异常干扰您的调试,您可以开始抛出从 ArgumentException 或 ValidationException 派生的自定义异常,并将 VS 配置为在抛出此自定义异常且用户未处理时不会中断

关于wpf - WPF 中使用 ValidatesOnExceptions 进行数据验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12349050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com