【问题标题】:Inheriting from one baseclass that implements INotifyPropertyChanged?从一个实现 INotifyPropertyChanged 的​​基类继承?
【发布时间】:2012-01-31 09:21:45
【问题描述】:

我有这个 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 在这里(2Times),红色下划线,它说:

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..

【问题讨论】:

标签: c# wpf inotifypropertychanged base


【解决方案1】:

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

【讨论】:

  • @eMi:我说你应该使用方法,设置为protected只是这样做的必要步骤。不要试图引发事件。
【解决方案2】:

改变派生类如下:

public class SchemaDifferenceViewModel : BaseViewModel
{
    private string firstSchemaToCompare;

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

【讨论】:

    【解决方案3】:

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

    这是你可以使用mixin的教科书地方

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

    【讨论】:

      猜你喜欢
      • 2011-04-15
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2016-01-13
      • 2023-03-18
      • 2011-09-12
      相关资源
      最近更新 更多