MVVM base view model class
I am working on creating a base view model class. ViewModelBase is an abstract class and I want to define the properties that I want all my other derived view models to implement.
One of the properties is an ObservableCollection:
public abstract ObservableCollection<???> Items { get; set; }
The classes that derive from this base class will have different types of Items defined (ObservableCollection<Person>
, Obs开发者_如何学JAVAervableCollection<Car>
).
If I set the ObservableCollection type to object
in ViewModelBase, it would require me to do a lot of different casting in the derived classes to get it to work.
Is this the right approach?
I'm not quite sure why you would want to make it so generic, but if you did, I'd recommend that you make the abstract base class generic as well:
public abstract class ViewModelBase<T>
{
public abstract ObservableCollection<T> Items { get; set; }
}
I hope you also make sure that your ViewModelBase implements INotifyPropertyChanged.
public abstract ObservableCollection<TYPE> Items { get; set; }
You can define the TYPE in many ways, including when using/inheriting from the base class, or Interface.
If you are creating a base view model for all the view models in your application, then it is unlikely that every single one will be holding an observable collection.
You can consider using composition instead of inheritance (or more likely, as well as inheritance) to add common functionality to your view models.
For example:
// Base for ALL view models implements necessary interfaces.
public abstract class BaseViewModel : INotifyPropertyChanged, IDisposable
{
// Functionality useful to ALL view models
public string DisplayName { get; }
// etc.
...
}
// Generic collection view model implementing functionality required by
// all collection view models.
public abstract class CollectionViewModel<T> : BaseViewModel
{
public abstract ObservableCollection<T> Items { get; set; }
}
// Specific collection view model using generic one through composition
public class PersonCollectionViewModel : BaseViewModel
{
public CollectionViewModel<Person> PersonCollection { get; }
// other functionality not included in all collection view models.
// ...
}
Define some class {Entity} that can be a base class of Car and of a Person: you will get what you want + strong typing.
You want to make your base class generic
Then you can have a defition like this
public abstract class ViewModelBase<T>
{
public abstract ObservableCollection<T> Items { get; set; }
}
If you want a list of viewmodels then I would recommend creating a non generic base class that the generic one inherits off and have a list of that
public abstract class NonGenericBaseViewModel
{
ObservableCollection<object> ItemsAsObjects{get;set;}
}
public abstract class ViewModelBase<T> : NonGenericBaseViewModel
{
public ObservableCollection<T> Items { get; set; }
}
then you can have an
ObservableCollection<NonGenericBaseViewModel>
if you want
精彩评论