Reputation: 23
I am new in wpf and i trying to make a validation textbox of some showdialog window. i already make a validation for empty dield and spaces but i need to add a validation for numbers that bigger than some max value that i passed to the dialog but dont know how to use it for ValidationRule Class.
this is my ValidationRule Class:
public class CustomValidationRule : ValidationRule
{
public int kMax
{
get { return kMax; }
set { kMax = value; }
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (string.IsNullOrEmpty(value.ToString()))
return new ValidationResult(false, "No number was entered!");
if (value.ToString().Contains(' '))
return new ValidationResult(false, string.Format("No spaces allowed!" );
try
{
int num = Convert.ToInt32(value);
if (num == 0 || num > kMax)
return new ValidationResult(false, string.Format("Number must be in range of (0,{0})", kMax));
}
catch (FormatException fe)
{
return new ValidationResult(false, fe.Message);
}
return ValidationResult.ValidResult;
}
}
and this is my window code:
public partial class kInputWindow : Window
{
public string ResultText { get; set; }
public int kMax { get; set; }
public kInputWindow(string question,int kMax)
{
InitializeComponent();
lblQuestion.Content = question;
this.DataContext = this;
this.kMax = kMax;
}
private void btnDialogOk_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
public string Answer
{
get { return txtAnswer.Text; }
}
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
}
when i create the dialog at the main window i doing it like this:
kInputWindow kInput = new kInputWindow(question, lines);
kInput.ShowDialog();
and now kinput got the value i need but i dont know how to pass it for my ValidationRule Class
Upvotes: 1
Views: 1023
Reputation: 5467
In WPF validation is usually set in the xaml. When you create your binding for your textbox you can also specify it's validation rules e.g.;
<Binding.ValidationRules>
<CustomValidationRule/>
</Binding.ValidationRules>
You can add several validation rules if you wish. When the value that is being bound changes it gets passed to the validation rule object and is validated automatically so there is no need to manually pass in the value. You will need to create an instance of your validation rule within your xaml. This article gives a good introduction
Upvotes: 0