从一个实现INotifyPropertyChanged的基类继承?

时间:2012-01-31 09:21:46

标签: c# wpf inotifypropertychanged base

我有这个BaseClass:

public class BaseViewModel : INotifyPropertyChanged
{
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

和另一个班级:

public class SchemaDifferenceViewModel : BaseViewModel
{
    private string firstSchemaToCompare;

    public string FirstSchemaToCompare
    {
        get { return firstSchemaToCompare; }
        set
        {
            firstSchemaToCompare = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("FirstSchemaToCompare"));
                //StartCommand.RaiseCanExecuteChanged();
            }
        }
    }

PropertyChanged在这里(2次),红色下划线,它说:

Error   1   The event BaseViewModel.PropertyChanged' can only appear on the left hand side of += or -= (except when used from within the type 'SchemaDifferenceFinder.ViewModel.BaseViewModel')

我做错了什么?我只将PropertyChangedEvent扫描到一个新类:BaseViewModel ..

3 个答案:

答案 0 :(得分:6)

不能在声明它的类之外引发事件,使用基类中的方法来引发它(make OnPropertyChanged protected)。

答案 1 :(得分:3)

更改派生类如下:

public class SchemaDifferenceViewModel : BaseViewModel
{
    private string firstSchemaToCompare;

    public string FirstSchemaToCompare
    {
        get { return firstSchemaToCompare; }
        set
        {
            firstSchemaToCompare = value;
            OnPropertyChanged("FirstSchemaToCompare");
        }
    }

答案 2 :(得分:0)

在我看来,为INPC制作基类是一个糟糕的设计。

这是您可以使用mixin

的教科书

简而言之,它允许您提供接口成员的默认实现。你仍然可以从一个真正有趣的类继承=)