Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataValidation in WPF using ValidatesOnExceptions

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>
like image 352
Muhammad Ummar Avatar asked Oct 16 '25 00:10

Muhammad Ummar


1 Answers

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

like image 126
Jogy Avatar answered Oct 18 '25 04:10

Jogy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!