您可以尝试以下几种使用 IDataErrorInfo 的方法。它们都依赖于提高 INotifyPropertyChanged 通知将导致重新评估绑定验证的事实。
有两个文本框。一种使用异步绑定并假设 Web 服务调用是同步的。第二个使用同步绑定并假设 Web 服务调用是异步的。
Xaml
<Window.DataContext>
<WpfValidationUpdate:ViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Margin="5" Grid.Row="0" Text="{Binding Text1, IsAsync=True, ValidatesOnDataErrors=True}"/>
<TextBox Margin="5" Grid.Row="1" Text="{Binding Text2, ValidatesOnDataErrors=True}"/>
</Grid>
查看模型
public class ViewModel : IDataErrorInfo, INotifyPropertyChanged
{
private string _text1;
private string _text2;
private bool _text1ValidationError;
private bool _text2ValidationError;
#region Implementation of IDataErrorInfo
public string this[string columnName]
{
get
{
if(columnName == "Text1" && _text1ValidationError)
{
return "error";
}
if(columnName == "Text2" && _text2ValidationError)
{
return "error";
}
return string.Empty;
}
}
public string Error
{
get
{
return string.Empty;
}
}
public string Text1
{
get { return _text1; }
set
{
_text1 = value;
OnPropertyChanged("Text1");
// Simulate web service synchronously taking a long time
// Relies on async binding
Thread.Sleep(2000);
_text1ValidationError = true;
OnPropertyChanged("Text1");
}
}
public string Text2
{
get { return _text2; }
set
{
_text2 = value;
OnPropertyChanged("Text2");
// Simulate web service asynchronously taking a long time
// Doesn't rely on async binding
Task.Factory.StartNew(ValidateText2);
}
}
private void ValidateText2()
{
Thread.Sleep(2000);
_text2ValidationError = true;
OnPropertyChanged("Text2");
}
#endregion
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if(handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}