Data validation in 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()
{
Initialize开发者_开发百科Component();
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.
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.
For DataValidatation you need to do the following:
Implement System.ComponentModel.IDataErrorInfo in your Data Class
You need to add ValidationRule to your Binding
The Debugger seems to ignore the fact that the exception generated here in actually caught by the binding engine. When you start your program outside Visual Studio, you should get the desired behaviour.
To avoid having the debugger break on your validation, you could use
public int Valore
{
get { //... }
[System.Diagnostics.DebuggerStepThrough()]
set { //... }
}
Or, better yet, do not use exceptions for data validation, but have a look at the IDataErrorInfo interface. After all, invalid user input is not exceptional, but the norm. =)
Use ValidationRules property on your text binding binding
<TextBox>
<TextBox.Text>
<Binding Path=Valore, Mode=TwoWay>
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
if you enter wrong value your text box border will get red
There are many ways to perform validation. If you're using MVVM then probably IDataErrorInfo
is the way to go.
I would pair that with FluentValidation to simplify things.
精彩评论