最簡單的方法是在二傳手提出一個PropertyChanged
通知爲需要像bathineni suggests
private DateTime StartDate
{
get { return _startDate; }
set
{
if (_startDate != value)
{
_startDate = value;
RaisePropertyChanged("StartDate");
RaisePropertyChanged("EndDate");
}
}
}
private DateTime EndDate
{
get { return _endDate; }
set
{
if (_endDate!= value)
{
_endDate= value;
RaisePropertyChanged("StartDate");
RaisePropertyChanged("EndDate");
}
}
}
但是要驗證這兩個屬性,如果不適合你,我想出了一個辦法,驗證一組屬性在一起,雖然你的類除了擁有INotifyPropertyChanged
實施INotifyPropertyChanging
(我用的EntityFramework,默認情況下其類實現兩個接口)
擴展方法
public static class ValidationGroup
{
public delegate string ValidationDelegate(string propertyName);
public delegate void PropertyChangedDelegate(string propertyName);
public static void AddValidationGroup<T>(this T obj,
List<string> validationGroup, bool validationFlag,
ValidationDelegate validationDelegate,
PropertyChangedDelegate propertyChangedDelegate)
where T : INotifyPropertyChanged, INotifyPropertyChanging
{
// This delegate runs before a PropertyChanged event. If the property
// being changed exists within the Validation Group, check for validation
// errors on the other fields in the group. If there is an error with one
// of them, set a flag to true.
obj.PropertyChanging += delegate(object sender, PropertyChangingEventArgs e)
{
if (validationGroup.Contains(e.PropertyName))
{
foreach(var property in validationGroup)
{
if (validationDelegate(property) != null)
{
validationFlag = true;
break;
}
}
}
};
// After the Property gets changed, if another field in this group was
// invalid prior to the change, then raise the PropertyChanged event for
// all other fields in the Validation Group to update them.
// Also turn flag off so it doesn't get stuck in an infinite loop
obj.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
{
if (validationGroup.Contains(e.PropertyName))
{
if (validationFlag && validationDelegate(e.PropertyName) == null)
{
validationFlag = false;
foreach(var property in validationGroup)
{
propertyChangedDelegate(property);
}
}
}
};
}
}
要使用它,請將以下調用添加到應該驗證一組屬性的任何類的構造函數中。
this.AddValidationGroup(
new List<string> { "StartDate", "EndDate" },
GetValidationError, OnPropertyChanged);
我已經在一個驗證組中測試了多達3個屬性,它似乎工作正常。
只是要拋出一種替代方法,當兩個規則被打破時,你能否把兩個盒子都變成紅色?如果是這樣,你只需要提出一個propertychanged事件。 – Josh
@Josh很想去,但我不知道如何手動提高各個屬性的驗證事件 – Rachel
我退出了使用驗證事件。我認爲他們應該開火,而他們沒有或他們開火,邊界不突出,我對他們的問題太多了。我使用綁定到有效的布爾表示的紅色邊框樣式。我也將工具提示綁定到消息屬性。然後,當一個值改變我驗證它並適當地設置屬性。 – Josh