使用WPF在c#中对用户输入进行纯字母验证
本文关键字:验证 输入 用户 WPF 使用 | 更新日期: 2023-09-27 17:49:13
我对使用c#相当陌生,我一直在做一个小游戏来帮助我习惯这种语言。我希望玩家能够在整个游戏过程中输入一个只能使用字母的名字;但是,我在试图让验证工作时遇到了几个问题。
以下是XAML代码:<Window x:Class="COMP4_Project.InputWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="New Game" Height="120" Width="250" ResizeMode="CanMinimize">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label>Enter name:</Label>
<TextBox x:Name="userInput" Grid.Column="2" Margin="0,0,0,0"></TextBox>
<Button x:Name="Confirm" Click="Confirm_Click" Grid.Row="2" Width="80" Height="25" Content="Confirm" Margin="0,10,0,41" />
<Button x:Name="Cancel" Click="Cancel_Click" Grid.Row="2" Grid.Column="1" Width="80" Height="25" Content="Cancel" HorizontalAlignment="Right" Margin="54,10,0,41" />
</Grid>
下面是我的codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace COMP4_Project
{
/// <summary>
/// Interaction logic for InputWindow.xaml
/// </summary>
public partial class InputWindow : Window
{
public InputWindow()
{
InitializeComponent();
}
private void Confirm_Click(object sender, RoutedEventArgs e)
{
string playerName;
string userInput = "";
Regex r = new Regex("^[a-zA-Z]*$");
if (r.IsMatch(userInput))
{
MessageBox.Show("onlyletter");
playerName = userInput;
Window win = new GameWindow();
win.Owner = this;
win.ShowDialog();
}
else
{
MessageBox.Show("Only letters permitted. Try again!");
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
我已经尝试了几种方法来获得验证工作;这是目前为止我在不破坏应用程序的情况下得到的最接近的结果。尽管使用了验证,但它似乎接受任何输入,包括带有数字的输入和根本没有键入任何内容的输入(我试图将正则表达式中的*更改为a +来解决这个问题,但是当我这样做时,它不会接受任何输入)。
我觉得这个问题与我如何为userInput声明变量有关,但我不确定如何在没有更多错误弹出的情况下解决它。
您将userInput
定义为Click
事件中的空字符串。
private void Confirm_Click(object sender, RoutedEventArgs e)
{
string playerName;
string userInput = ""; // An empty string is a match for your pattern
Regex r = new Regex("^[a-zA-Z]*$");
if (r.IsMatch(userInput))
{
...
将userInput
设置为他们输入名称的文本框中的值。
private void Confirm_Click(object sender, RoutedEventArgs e)
{
string playerName;
string userInput = userInput.Text;
Regex r = new Regex("^[a-zA-Z]*$");
if (r.IsMatch(userInput))
{
...
您正在这样做:
string userInput = "";
代替:
string user = userInput.Text;