這個問題可能看起來有點微不足道,但它可能不是。我只是想知道下面哪兩種情況更適合間接財產通知,或者有更好的辦法。間接財產通知
場景:
我有兩個屬性,第一個是叫HoldingObject對象,第二個是一個名爲IsHoldingObject布爾值,它是假的,如果HoldingObject == null,否則這是真的。我只是想知道什麼是IsHoldingObject最好的通知機制:
情況(A) - 通知IsHoldingObject從HoldingObject proeperty改變:
public class NotifyingClass1 : INotifyPropertyChanged
{
private object _holdingObject;
public object HoldingObject
{
get { return _holdingObject; }
set
{
if (_holdingObject != value)
{
_holdingObject = value;
NotifyPropertyChanged("HoldingObject");
// Notify from the property that is being checked
NotifyPropertyChanged("IsHoldingObject");
}
}
}
public bool IsHoldingObject { get { return this.HoldingObject == null; } }
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
情況(B) - 通知IsHoldingObject從IsHoldingObject直接改變通過從HoldingObject屬性設置爲false或真:因爲它需要更少的代碼,但我不知道它是怎麼推薦做
public class NotifyingClass2 : INotifyPropertyChanged
{
private object _holdingObject;
public object HoldingObject
{
get { return _holdingObject; }
set
{
if (_holdingObject != value)
{
_holdingObject = value;
NotifyPropertyChanged("HoldingObject");
// 1) Set the property here
this.IsHoldingObject = _holdingObject != null;
}
}
}
private bool _isHoldingObject;
public bool IsHoldingObject
{
get { return _isHoldingObject; }
set
{
if (_isHoldingObject != value)
{
_isHoldingObject = value;
// 2) Notify directly from the property
NotifyPropertyChanged("IsHoldingObject");
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
我個人偏向於第一種。讓我知道如果有另一種(更好的)方式。
謝謝!
+1這正是我要做的事。 – rossisdead 2010-04-19 21:15:40