6

I have this BaseClass:

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

    public event PropertyChangedEventHandler PropertyChanged;
}

and a other class:

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 is here ( 2Times ), red underlined, it says:

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')

What I'm doing wrong? I only swept the PropertyChangedEvent to a new class: BaseViewModel..

eMi
  • 5,540
  • 10
  • 60
  • 109

3 Answers3

6

You cannot raise the event outside the class it is declared in, use the method in the base class to raise it (make OnPropertyChanged protected).

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • 1
    @eMi: I said you should use the method, making it `protected` is just the necessary step to do so. Do not try to raise the event. – H.B. Jan 31 '12 at 09:27
3

Change derived class as follow:

public class SchemaDifferenceViewModel : BaseViewModel
{
    private string firstSchemaToCompare;

    public string FirstSchemaToCompare
    {
        get { return firstSchemaToCompare; }
        set
        {
            firstSchemaToCompare = value;
            OnPropertyChanged("FirstSchemaToCompare");
        }
    }
Amit
  • 929
  • 8
  • 27
0

Making a base class for INPC is bad design in my opinion.

This is the textbook place where you could use a mixin

In short, it allows you to provide a default implementation of an interface's members. You would still be able to inherit from an actually interesting class =)

Louis Kottmann
  • 16,268
  • 4
  • 64
  • 88