0
我正在创建一个应用程序,用户名必须输入到textBox
。我暂停了一个教程来做到这一点。但是,当我点击按钮来验证textBox
,并且我没有输入名称时,我没有收到验证错误,提示“必须输入姓名”。相反,我必须在textBox
中输入文本,然后删除文本,然后单击按钮获取错误消息。我认为这是因为我使用OnProperyChanged
方法完成了它。有没有一种方法可以验证我的textBox
,而无需先输入文本然后删除文本?验证文本框wpf
我的代码休耕
XAML
<TextBox.Text>
<Binding Path="Name" Mode="TwoWay" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<local:NameValidator></local:NameValidator>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
NameValidator.cs
public class NameValidator : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value.ToString().Length ==0)
return new ValidationResult(false, "value cannot be empty.");
else
{
if (value.ToString().Length > 3)
return new ValidationResult(false, "Name cannot be more than 3 characters long.");
}
return ValidationResult.ValidResult;
}
}
xaml.cs
if (!Validation.GetHasError(tbxName))
{
// do the proicessing
}
private void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}