Man*_*han 6 .net c# inotifypropertychanged
我有一个名为Page的父对象,它有一个名为Control的对象列表:
public class Page
{
List<CustomControl> controls {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
CustomControl类具有以下定义:
public class CustomControl
{
string Name {get;set;}
string Value {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
比方说,Page类有两个CustomControls A和B.当Custom Control A的属性Value发生变化时,可以通知自定义控件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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9142 次 |
| 最近记录: |