Reputation: 21
I am trying to validate the input that is entered in the Datagrid in WPF.
I've added a validation rule to the XAML.
The input is an object anymore but a string or int. Though the method i use expects an object.
How can i solve the problem and make it work with an int or string. The input can only be an int between 1 and 20.
XAML:
<DataGridTextColumn Header="Niveau">
<DataGridTextColumn.Binding>
<Binding Path="Niveau" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<valRule:NiveautredeValidationRule />
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
C#
public class NiveautredeValidationRule : ValidationRule
{
public override System.Windows.Controls.ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
NiveaudoelenViewModel doel = (value as BindingGroup).Items[0] as NiveaudoelenViewModel;
if (doel.Niveau <= 0 || doel.Niveau > 20)
{
return new System.Windows.Controls.ValidationResult(false, "Niveau moet tussen de 1 en 20 zijn!");
}
else
{
return System.Windows.Controls.ValidationResult.ValidResult;
}
}
}
Upvotes: 1
Views: 8017
Reputation: 7440
You should consider updating the acepted answer to this,
this eliminates the try catch
and use TryParse instead
public override System.Windows.Controls.ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
int myInt;
if (!int.TryParse(System.Convert.ToString(value), out myInt))
return new ValidationResult(false, "Illegal characters");
if (myInt < 0 || myInt > 20)
{
return new ValidationResult(false, "Please enter a number in the range: 0 - 20");
}
else
{
return new ValidationResult(true, null);
}
}
Upvotes: 1
Reputation: 1549
You can try this :
public override System.Windows.Controls.ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
int myInt = 0;
try
{
if (((string)value).Length > 0)
myInt = int.Parse((String)value);
}
catch (Exception e)
{
return new ValidationResult(false, "Illegal characters or " + e.Message);
}
if (myInt < 0 || myInt > 20)
{
return new ValidationResult(false,
"Please enter a number in the range: 0 - 20");
}
else
{
return new ValidationResult(true, null);
}
}
Source : https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-implement-binding-validation
Upvotes: 2