我一直在努力从派生类订阅基类事件。目的是每次获取propertychanged时在我的基类中引发事件,从而在我的派生类中运行一个方法。这是我的代码的简化版本:
namespace MyNamespace
{
public delegate void EventHandler();
[Serializable]
public class ChartGroupCollection : ObservableCollection<ChartGroup>, INotifyCollectionChanged
{
public ChartGroupCollection()
{
base.DirtyFlagging += new EventHandler(MethodIWantToRun); //subscription to event
}
void MethodIWantToRun()
{
SomeVariable++;
}
#region NotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
[Serializable]
public class ChartGroup : INotifyPropertyChanged
{
public event EventHandler<EventArgs> DirtyFlagging;
protected virtual void OnDirtyFlagging(EventArgs e)
{
EventHandler<EventArgs> handler = DirtyFlagging;
if (handler != null)
{
handler(this, e);
}
}
public ChartGroup()
{
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
DirtyFlagging.Invoke(this, someeventargs); //Where i want to invoke the event
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
答案 0 :(得分:0)
我想你想做这样的事情
public class ChartGroupCollection : ObservableCollection<ChartGroup>
{
public int SomeVariable { get; set; }
public ChartGroupCollection()
{
CollectionChanged += ChartGroupCollection_CollectionChanged;
}
void ChartGroupCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (ChartGroup item in e.OldItems)
{
item.PropertyChanged -= item_PropertyChanged;
}
}
if (e.NewItems != null)
{
foreach (ChartGroup item in e.NewItems)
{
item.PropertyChanged += item_PropertyChanged;
}
}
}
void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
MethodIWantToRun();
}
private void MethodIWantToRun()
{
SomeVariable++;
}
}
public class ChartGroup : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
int _myProperty;
public int MyProperty
{
set {
_myProperty = value;
NotifyPropertyChanged();
}
}
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
致电触发事件:
ChartGroupCollection chartGroupCollection = new ChartGroupCollection();
var group = new ChartGroup();
chartGroupCollection.Add(group);
group.MyProperty = 3;