Create a new viewmodel base class that adds a few additional properties

Aug 20, 2013 at 9:24 PM
I have the need to add a few additional properties to my application's "ViewModelBase" class but am struggling to derive my new base class from the provided ViewModelBase while maintaining the existing NotifyPropertyChanged functionality.

I'm sure this is less of a Simple MVVM question and more of a C#/generics question, but I thought I might get some quick advice here.

If anyone could post a simple example of deriving a new "base" class from the existing ViewModelBase with the addition of a new property and then deriving another class from the new base class, that'd be great. So, something like:

class MyViewModelBase : ViewModelBase

and then...

class MyRealClass : MyViewModelBase

Thanks in advance.

Jeff
Aug 20, 2013 at 10:53 PM
I just came up with something that seems to work, though if anyone has further suggestions, that'd be great. Basically, I created my new "base" class like:
public abstract class WorkspaceViewModelBase : ViewModelBase<WorkspaceViewModelBase>
{
    public WorkspaceViewModelBase() { }

    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            this.NotifyPropertyChanged(m => m.Name, propertyChanged);
        }
    }
    
    ....
}
and then I derived several ViewModels from the above like:
public class DataGridViewModel : WorkspaceViewModelBase
{
    public DataGridViewModel() 
    { 
      Name = "DataGridView"; 
    }

    private DataTable _tableData;
    public DataTable TableData
    {
        get { return _tableData; }
        set
        {
            _tableData = value;
            this.NotifyPropertyChanged(m => m.TableData, propertyChanged);
        }
    }

    ....
}
My main struggle was in getting the NotifyPropertyChanged code to compile, but the above seems to work.

Does this look reasonable?

Thanks,

Jeff
Jul 17, 2015 at 5:18 AM
This post is old but posting this just for the record. One solution seem to work that is when you pass in the model in lambda, just use the property in derived model directly without ModelBase.Property.
public class DataGridViewModel : WorkspaceViewModelBase
{
    public DataGridViewModel() 
    { 
      Name = "DataGridView"; 
    }

    private DataTable _tableData;
    public DataTable TableData
    {
        get { return _tableData; }
        set
        {
            _tableData = value;
            this.NotifyPropertyChanged(m => TableData);
        }
    }

    ....
}