我正在尝试实现ValidationRule,以验证用户在TextBox
中只输入alphabets
。我下面的代码与上面链接的示例有点不同,其中属性Min和Max是固定数字;而在我的情况下,属性CCD_ 3包含字母表的范围。
问题:在MainWindow.xaml
文件的以下部分(如底部所示(中,我应该用什么替换????
?我在这里发现了类似的东西,但他们声明了一个属性MustEndWith
,指示值应该以单词.def
结尾——这与说所有字符都必须是字母不同。
<Binding.ValidationRules>
<local:AlphabetsOnlyValidationRule AlphabetsOnly="????" />
</Binding.ValidationRules>
代码:
public class AlphabetsOnlyValidationRule : ValidationRule
{
public string AlphabetsOnly { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string sVal = value as string;
if (sVal == null)
{
return new ValidationResult(false, "Please enter some text");
}
if (!sVal.ToList().All(c=>char.IsLetter(c)))
{
return new ValidationResult(false, "First Name should contains alphabets only"));
}
return new ValidationResult(true, null);
}
}
主窗口.xaml:
<Window x:Class="WPF_DeleteNow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
.....
xmlns:local="clr-namespace:MyWPFProject"
mc:Ignorable="d">
<Window.Resources>
<local:AlphabetsOnlyValidationRule x:Key="AlphabetsOnlyKey"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
.....
</Grid.RowDefinitions>
<TextBox Name="txtFirstName">
<TextBox.Text>
<Binding Path="FirstName" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:AlphabetsOnlyValidationRule AlphabetsOnly="??????" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</Grid>
</Window>
您不需要一个属性来验证字符串是否只包含字母。只需删除AlphabetsOnly
属性并使用正则表达式执行验证:
public class AlphabetsOnlyValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string sVal = value as string;
if (string.IsNullOrEmpty(sVal))
{
return new ValidationResult(false, "Please enter some text");
}
if (System.Text.RegularExpressions.Regex.IsMatch(sVal, @"^[a-zA-Z]+$"))
{
return new ValidationResult(false, "First Name should contains alphabets only");
}
return new ValidationResult(true, null);
}
}