我是wpf的新手,我正在尝试制作一些showdialog窗口的验证文本框。我已经对空的dield和空格进行了验证,但我需要对大于我传递给对话框的某个最大值的数字添加验证,但不知道如何将其用于ValidationRule类。
这是我的验证规则类:
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;
}
}
这是我的窗口代码:
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);
}
}
当我在主窗口创建对话框时,我这样做:
kInputWindow kInput = new kInputWindow(question, lines);
kInput.ShowDialog();
现在kinput得到了我需要的值,但我不知道如何将其传递给我的ValidationRule类
在WPF中,验证通常在xaml中设置。当你为你的文本框创建绑定时,你也可以指定它的验证规则,例如。;
<Binding.ValidationRules>
<CustomValidationRule/>
</Binding.ValidationRules>
如果愿意,可以添加几个验证规则。当绑定的值发生更改时,它会被传递到验证规则对象并自动进行验证,因此无需手动传入值。您需要在xaml中创建验证规则的实例。这篇文章很好地介绍了