Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data validation in wpf

Tags:

c#

validation

wpf

in my code i've this:

class Data
{
    private int valore;
    public int Valore
    {
        get 
        {
            return valore;
        }
        set
        {
            if (value > 10 || value < 0)
            {
                throw new ArgumentException("Insert a value between 0 and 10");
            }                    
            valore = value;                
        }
    }
}

Then i've:

Data dati = new Data { Valore = 6 };

    public MainWindow()
    {
        InitializeComponent();                      

        this.DataContext = dati;
    }

and in XAML i've:

<TextBox Height="23" Width="120" Text="{Binding Path=Valore, Mode=TwoWay, ValidatesOnExceptions=True}"

The problem is that when I insert a value greater than 10, I can't see the red border around the TextBox, but instead my application throws an un-handled exception.

like image 617
matte Avatar asked Nov 04 '22 19:11

matte


1 Answers

MSDN WPF Validation

You are doing this incorrectly, the reason that your program is crashing from an unhandled exception is that you are throwing and unhandled exception.

like image 58
msarchet Avatar answered Nov 09 '22 06:11

msarchet