0

我在 WPF 中有两个文本框。命名为 txt1 和 txt2。

在 txt1 的 lostFocus 我写

If txt1.Text is nothing then 
    txt1.Focus
End If

在 txt2 的 lostFocus 事件中,我写

If txt2.Text is nothing then
    txt2.Focus
End If

现在,如果 txt1 和 txt2 都为空并且用户在 txt1 中按 TAB 键,则会出现问题。程序进入无限循环。我的意思是光标到达 txt1 并无限次到达 txt2。根据我的代码,我知道这是正常行为。

所以我想要验证事件来避免上述问题。但我在 WPF 中找不到。那么我应该使用哪个事件?

4

2 回答 2

1

我不是 VB 编码员,因此无法为您编写确切的代码,但这是您应该做的。为事件 PreviewLostKeyboardFocus 添加事件处理程序。如果文本为空,则在事件处理程序中将 e.Handled 设置为 true。示例 C# 代码。我写了一个通用的处理程序。

private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    if (string.IsNullOrEmpty((sender as TextBox).Text))
    {
        e.Handled = true;
    }
}
于 2013-06-10T14:45:56.353 回答
0

更好的解决方案可能是允许用户离开空/空文本框,但要么将文本恢复为初始值(如果有的话),要么提供验证错误。使用 IDataErrorInfo 提供验证错误相对容易。

作为一名软件用户,当应用程序阻止我离开某个领域时,我会感到恼火。

重设值法

有关如何维护和获取先前值的信息,请参阅此 stackoverflow 方法。在 LostFocus 事件中,如果当前值无效,您可以将成员变量设置回 _oldValue。 确定文本框在失去焦点事件中的先前值?WPF

验证方法

这两个日期存储在模型或视图模型类中。在该类中实现 IDataErrorInfo ( http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo(v=vs.95).aspx )。然后在您的 xaml 中,您可以显示验证错误。

//This is your model/viewmodel validation logic
public string this[string columnName]
{
    get
    {
        string result = null;
        if (columnName == "FirstName")
        {
            if (string.IsNullOrEmpty(FirstName))
                result = "Please enter a First Name";
        }
        if (columnName == "LastName")
        {
            if (string.IsNullOrEmpty(LastName))
                result = "Please enter a Last Name";
        }
       if (columnName == "Age")
        {
            if (Age < = 0 || Age >= 99)
                result = "Please enter a valid age";
        }
        return result;
    }
}

//Here is a sample of a xaml text block
<textbox x:Name="tbFirstName" Grid.Row="0" Grid.Column="1" Validation.Error="Validation_Error" Text="{Binding UpdateSourceTrigger=LostFocus, Path=FirstName, ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />

您还可以查看这些其他 StackOverflow 帖子 - 什么是 IDataErrorInfo 以及它如何与 WPF 一起使用? IDataErrorInfo 通知

于 2013-06-10T21:19:58.530 回答