如果我要在用户在文本字段中输入内容时(而不是在窗口弹出时)运行验证,该怎么办。这是示例图片:
在我执行此窗口的示例图像中,它会自动验证。当我输入内容时,我希望它检查验证。
这是验证中的代码片段:
public string Error
{
get { return null; }
}
public string this[string propertyName]
{
get
{
string error = string.Empty;
switch (propertyName)
{
case "Name":
if (string.IsNullOrEmpty(Name))
error = "Name is required!";
break;
case "Url":
if (string.IsNullOrEmpty(Url))
error = "Url is required!";
else if (!Regex.IsMatch(Url, @"(?:https?:\/\/)?(?:[\w]+\.)([a-zA-Z\.]{2,6})([\/\w\.-]*)*\/?"))
error = "Url is invalid";
break;
case "Price":
if (Price < 0)
error = "Price cannot be negative!";
break;
default:
break;
}
return error;
}
}
这是我的UI中的代码段:
<!--Product Name-->
<Label Content="Name:" />
<TextBox x:Name="txtName"
Grid.Column="2"
Validation.Error="ValidationError"
Text="{Binding Name,
Mode=TwoWay,
ValidatesOnDataErrors=True,
NotifyOnValidationError=True,
UpdateSourceTrigger=PropertyChanged}" />
<!--Product Url-->
<Label Grid.Row="2" Content="Url:" />
<TextBox x:Name="txtUrl"
Grid.Row="2"
Grid.Column="2"
Validation.Error="ValidationError"
Text="{Binding Url,
Mode=TwoWay,
ValidatesOnDataErrors=True,
NotifyOnValidationError=True,
UpdateSourceTrigger=PropertyChanged}"/>
如果用“当我输入某物时”表示“每次我按一个键”,则将BindingUpdateSourceTrigger
值更改PropertyChanged
为TextBox上的。这意味着,每当更改TextBox的值时,它将自动更新绑定的对象并触发IDataErrorInfo
接口调用以更新的状态TextBox
。
更新:
您需要实现INotifyPropertyChanged
接口以允许IDataErrorInfo
其正常运行。
public class MyObject : INotifyPropertyChanged, IDataErrorInfo
{
public event PropertyChangedEventHandler PropertyChanged;
private string _myValue;
public string MyValue
{
get { return _myValue; }
set
{
_myValue = value;
OnPropertyChanged("MyValue");
}
}
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public string Error
{
get { return null; }
}
public string this[string columnName]
{
get
{
string returnValue = null;
switch (columnName)
{
case "MyValue":
if MyValue != "expected"
returnValue = "MyValue is not expected";
}
return returnValue;
}
}
}
注意: IDataErrorInfo
仅MyValue
在更新通知到UI后才检索时调用(因此get
实现,而不是set
在索引器中)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句