我需要在Base和子类的情况下定义INotifyPropertyChanged

我有这个Base class

 public abstract class WiresharkFile { protected string _fileName; protected int _packets; protected int _packetsSent; protected string _duration; public int Packets { get { return _packets; } set { _packets = value; } } public int PacketsSent { get { return _packetsSent; } set { _packetsSent = value; } } } 

而这个子类:

 public class Libpcap : WiresharkFile, IDisposable, IEnumerable { .... } 

创建我的对象:

 WiresharkFile wiresahrkFile = new Libpcap(file); 

我的collections:

 public ObservableCollection wiresharkFiles { get; set; } 

发送包:

 wiresahrkFile.Sendpackets(); 

此时我所有的wiresahrkFilewiresahrkFile类型)属性都在改变,所以我想知道我需要在哪里定义这个INotifyPropertyChanged

如果你的xaml绑定到WiresharkFile的属性,那么WiresharkFile必须实现INotifyPropertyChanged,否则会导致内存泄漏( WPF编程的前3个内存泄漏导致陷阱 )。 如果只在Libpcap类上定义绑定,那么Libpcap必须实现INotifyPropertyChanged接口。 在我的项目中,我创建了一个INotifyPropertyChanged接口的基本实现,然后每个基本模型和基本视图模型都inheritance自该实现。 这里有一些基本代码:1。基本实现:

 public class BaseObservableObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } protected virtual void OnPropertyChanged(Expression> raiser) { var propName = ((MemberExpression)raiser.Body).Member.Name; OnPropertyChanged(propName); } protected bool Set(ref T field, T value, [CallerMemberName] string name = null) { if (!EqualityComparer.Default.Equals(field, value)) { field = value; OnPropertyChanged(name); return true; } return false; } } 

2.你的模特(在我看来):

 public abstract class WiresharkFile:BaseObservableObject { private string _fileName; private int _packets; private int _packetsSent; private string _duration; public int Packets { get { return _packets; } set { _packets = value; OnPropertyChanged(); } } public int PacketsSent { get { return _packetsSent; } set { _packetsSent = value; OnPropertyChanged(); } } } 

问候,