0

我正在尝试在 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;
}
4

2 回答 2

0

您在这里有几个问题:

1 - UI 元素不是“事件”,因此不存在 TextBox Event.

2 - UI 不是数据。因此,您应该在 ViewModel 中抽象您的逻辑并对其进行操作。

发布您的 XAML,我将编辑我的答案,显示实现此功能的正确方法。

于 2013-02-19T20:30:43.500 回答
0

您应该只将您绑定TextBox.Text到一个DateTime对象,如果输入的数据不正确,这将通过在TextBox.

如果这DateTime是强制性的,您应该设置一个ValidationRule供您TextBox验证,则无需将所有这些 UI 逻辑拖到您的模型中。

于 2013-02-19T22:57:42.340 回答