DataValidation in WPF using ValidatesOnExceptions

孤街醉人 提交于 2019-12-12 19:08:09

问题


I want to run a basic data validation sample in WPF using ValidatesOnException, but its simply not working, and as soon as my viewmodel throws ValidationException, my program crashes saying, ValidationException was unhandled by user code.

My View Model is

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");
        }
    }
}

My XAML is

<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>

回答1:


I ran your code, and when executed under a debugger, yes, the VS debugger stops at the throw, because there is no catch statement that handles that exception.

But when started without debugging, the applications does not crash - the edit box border turns red.

If you want to get rid of the exception, you may change the ViewModel to implement IDataErrorInfo interface instead of throwing exception.

If the exception is interfering with your debugging, you could for example, start throwing a custom exception derived from ArgumentException or ValidationException, and the configure VS to not break when this custom exception is thrown and user-unhandled



来源:https://stackoverflow.com/questions/12349050/datavalidation-in-wpf-using-validatesonexceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!