1
我是新的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類