原創|其它|編輯:郝浩|2012-08-22 02:19:33.000|閱讀 1788 次
概述:詳細講述了WPF4.5的異步數據驗證用法,并提供了其中的代碼,對于WPF4.5的使用會起到一定的幫助作用。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
WPF 4.5里面有什么?更多WPF4.5探秘系列文章
里面只有三樣東西:
需要說明的是,如果你返回false到HasErrors屬性時,如果沒有出現error就會發生綁定。
WPF4.5怎樣使用?
您必須在每個綁定到你的對象ValidatesOnDataErrors屬性設置為true。
在示例中創建了一個表單,顯示對象的屬性命名為“Person”。這里將解釋如何在綁定中啟用INotifyDataErrorInfo驗證:
<TextBox Text="{Binding Name,Mode=TwoWay,ValidatesOnNotifyDataErrors=True}"/>
該綁定將自己為ErrorsChanged事件進行注冊。每當綁定屬性事件發生時,這些控制將自動顯示error。前面已經指出,這只會出現在當HasErrors被設置為true時。
在驗證Person類時發生了延遲。在設置任何屬性時驗證都將發生,但它會因“WaitSecondsBeforeValidation ”而延遲數秒。
保存每個屬性下面的error并通過GetErros方法來提供。如果有其中的error出現那么HasErrors屬性將返回為true。以下是實現代碼:
public System.Collections.IEnumerable GetErrors(string propertyName)
{
List<string> errorsForName;
_errors.TryGetValue("Name", out errorsForName);
return errorsForName;
}
public bool HasErrors
{
get { return _errors.Values.FirstOrDefault(l => l.Count > 0) != null; }
}
private Dictionary<string, List<string>> _errors =
new Dictionary<string, List<string>>();
private void Validate()
{
Task waitTask = new Task(() => Thread.Sleep(
TimeSpan.FromSeconds(WaitSecondsBeforeValidation)));
waitTask.ContinueWith((_) => RealValidation());
waitTask.Start();
}
private object _lock = new object();
private void RealValidation()
{
lock (_lock)
{
//Validate Name
List<string> errorsForName;
if (!_errors.TryGetValue("Name", out errorsForName))
errorsForName = new List<string>();
else errorsForName.Clear();
if (String.IsNullOrEmpty(Name))
errorsForName.Add("The name can't be null or empty.");
_errors["Name"] = errorsForName;
if (errorsForName.Count > 0) RaiseErrorsChanged("Name");
//Validate Age
List<string> errorsForAge;
if (!_errors.TryGetValue("Age", out errorsForAge))
errorsForAge = new List<string>();
else errorsForAge.Clear();
if (Age <= 0)
errorsForAge.Add("The age must be greater than zero.");
_errors["Age"] = errorsForAge;
if (errorsForAge.Count > 0) RaiseErrorsChanged("Age");
}
最終,我創建了一個減低驗證事件error發生的RaiseErrorsChanged方法:
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public void RaiseErrorsChanged(string propertyName)
{
EventHandler<DataErrorsChangedEventArgs> handler = ErrorsChanged;
if (handler == null) return;
var arg = new DataErrorsChangedEventArgs(propertyName);
handler.Invoke(this, arg);
}
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:翻譯