【问题标题】:user-input validation by reg exp on WPF textbox通过 WPF 文本框中的正则表达式进行用户输入验证
【发布时间】:2015-08-07 13:00:31
【问题描述】:

我有一组输入验证。 数组的每一行代表一个输入验证;正则表达式检查的字符串和在验证失败时为用户显示的字符串:

public class myClass
{
     public static string[][] inputsInfo = new string[4][];

     static myClass()
     {
     // ID - 9 digits
     inputsInfo[0] = new string[2] { "^[0-9]{9}$", "exactly 9 digits (0-9)" };

     // only letters and possibly more than one word
     inputsInfo[1] = new string[2] { "^[A-Za-z]{2,}(( )[A-Za-z]{2,})*$", "only letters (A-Z) or (a-z)" };

     // Number - unlimited digits
     inputsInfo[2] = new string[2] { "^[0-9]+$", "only digits (0-9)" };

     // username, password
     inputsInfo[3] = new string[2] { "^[A-Za-z0-9]{6,}$", "at least 6 characters.\nOnly letters (A-Z) or (a-z) and digits (0-9) are allowed" };

     }
..............
..............
}

我有包含 WPF 文本框的窗口。有些字段具有相同的输入验证,这就是为什么我想将所有输入验证保存在数组中,所以我可以选择我现在需要的验证。

我有这个表格:

...............

        <TextBlock Grid.Row="2" Grid.Column="0" Text="First name"/>
        <TextBox x:Name="firstName" Grid.Row="2" Grid.Column="1"/>
        <Button Grid.Row="2" Grid.Column="2" Content="Search"/>

        <TextBlock Grid.Row="3" Grid.Column="0" Text="Last name"/>
        <TextBox x:Name="lastName" Grid.Row="3" Grid.Column="1"/>
        <Button Grid.Row="3" Grid.Column="2" Content="Search"/>

        <TextBlock Grid.Row="4" Grid.Column="0" Text="ID number"/>
        <TextBox x:Name="ID" Grid.Row="4" Grid.Column="1"/>
        <Button Grid.Row="4" Grid.Column="2" Content="Search"/>

...............

每个文本框都有一个带有 Click 事件的近按钮。 如何通过单击按钮执行输入验证?

有没有办法通过 XAML 代码做到这一点? 还是仅在 c# 代码的代码隐藏中?

任何帮助将不胜感激。

【问题讨论】:

  • 有人有解决办法吗?

标签: c# regex wpf validation user-input


【解决方案1】:

如何通过单击按钮执行输入验证?

为什么不在 ViewModel 上创建布尔标志来监视目标文本框的绑定文本属性以进行验证。示例

虚拟机:

public string FirstName { get { return _firstName; }
                          set { _firstname = value; 
                                PropertyChanged("IsFirstNameValid");
                                PropertyChanged("FirstName");
                              }
                        }

public bool IsFirstNameValid { get { return Regex.IsMatch( FirstName,
                                                           ValidationPatternFirstName); }}

XAML

<TextBox x:Name="firstName" 
         Text={Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />

然后,在对存储值 FirstName 进行任何更改时,布尔值 IsFirstNameValid 将在以后访问时准确反映该状态。

您也可以绑定到屏幕上的IsFirstNameValid 以显示或不显示图标,并将根据其状态进行更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    相关资源
    最近更新 更多