【问题标题】:DataValidation in WPF using ValidatesOnExceptions使用 Validates On Exceptions 在 WPF 中进行数据验证
【发布时间】: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


【解决方案1】:

我运行了您的代码,当在调试器下执行时,是的,VS 调试器在 throw 处停止,因为没有处理该异常的 catch 语句。

但是在没有调试的情况下启动时,应用程序不会崩溃 - 编辑框边框变为红色。

如果你想摆脱异常,你可以改变 ViewModel 来实现 IDataErrorInfo 接口而不是抛出异常。

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

【讨论】:

  • 谢谢,伙计。它对我帮助很大。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-20
  • 2014-05-23
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多