【发布时间】:2013-02-19 20:23:36
【问题描述】:
我正在尝试在 C# 中验证我的 WPF 程序,以检查用户是否已将日期输入到我的 DatePicker 事件中。如果用户没有输入日期,我希望它让用户在再次运行整个程序之前重新输入数据。如果用户输入的数字小于 1 或大于 10,我也希望它执行相同的操作。但是目前它只是继续执行程序的其余部分,导致它稍后中断。
我的“文本框”事件称为 UserInput,我的 DatePicker 称为“RequestedDate”
我的代码:
if (int.TryParse(UserInput.Text, out numberEntered))
{
while (DateRequested.SelectedDate == null)
{
MessageBox.Show("You have not input a valid date");
Output.Text = "Please try again";
}
while (numberEntered < 1 || numberEntered > 10)
{
MessageBox.Show("You can only book tickets with values more than one or less than 10");
Output.Text = "Please try again";
break;
}
Output.Text = "Number of tickets selected: " + UserInput.Text + "Date: " + DateRequested.Text;
}
【问题讨论】:
-
你不应该使用循环。只需使用
if...块或类似语句进行验证,并在出现问题时提示用户。让他们再次单击提交按钮并从头开始验证... -
您应该使用 wpf 方式并设置验证规则。你的代码的方式,你还不如使用winforms。
-
您的第一个 while-loop-that should-be-an-if-statement 中似乎缺少一个中断。
-
请注意,如果您不确定如何使用 ValidationRules,请查看 MSDN 上的示例msdn.microsoft.com/en-us/library/…
标签: c# wpf loops datepicker