我有一个名为 Page 的父对象,它有一个名为 Control 的对象列表:
public class Page
{
List<CustomControl> controls {get;set;}
}
CustomControl 类具有以下定义:
public class CustomControl
{
string Name {get;set;}
string Value {get;set;}
}
假设Page类有两个CustomControls A和B。当自定义控件A的属性值发生变化时是否可以通知自定义控件B,以便它可以更改其某些属性。
我正在考虑在 CustomControl 类上实现 INotifyPropertyChanged 事件,现在当同一类的另一个实例具有其 Modified 的某些属性时,如何通知 CustomControl 的实例。
最佳答案
public class CustomControl : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name == value) return;
_name = value;
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
private string _value;
public string Value
{
get { return _value; }
set
{
if (_value == value) return;
_value = value;
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
internal virtual void OnSiblingInPagePropertyChanged(object sender, PropertyChangedEventArgs args)
{
}
}
public class CustomControlObservableColletion : ObservableCollection<CustomControl>
{
// Required because, by default, it is not possible to find out which items
// have been cleared when the CollectionChanged event is fired after a .Clear() call.
protected override void ClearItems()
{
foreach (var item in Items.ToList())
Remove(item);
}
}
public class Page
{
public IList<CustomControl> Controls { get; private set; }
public Page()
{
var controls = new CustomControlObservableColletion();
controls.CollectionChanged += OnCollectionChanged;
Controls = controls;
}
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
RegisterControls(e.NewItems);
break;
case NotifyCollectionChangedAction.Replace:
RegisterControls(e.NewItems);
DeRegisterControls(e.OldItems);
break;
case NotifyCollectionChangedAction.Remove:
DeRegisterControls(e.OldItems);
break;
}
}
private void RegisterControls(IList controls)
{
foreach (CustomControl control in controls)
control.PropertyChanged += OnControlPropertyChanged;
}
private void DeRegisterControls(IList controls)
{
foreach (CustomControl control in controls)
control.PropertyChanged -= OnControlPropertyChanged;
}
private void OnControlPropertyChanged(object sender, PropertyChangedEventArgs e)
{
foreach (var control in Controls.Where(c => c != sender))
control.OnSiblingInPagePropertyChanged(sender, e);
}
}
关于c# - 当另一个对象的属性发生更改时通知一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3562738/