Archiv für den Monat: Mai 2010

Generic View Models in Silverlight

I like using Base-Classes for any kind of „Class-Group“. Very prominent groups are Models and ViewModels in Silverlight-Applications.

The ViewModel-Baseclass can hold any functionality, that applies to every ViewModel inheriting from it and, if we are talking about Generics, can be very convenient to use.

For example, if I want to apply the factory-pattern to my ViewModels and want every Model to have a static Create-Method I can simply implement this Method in the Base-Class.

Of cause, without Generics we are limited to the return-Type. We could now override this method in every specific ViewModel to at least return the right ancestor of ViewModelBase. An easier way is, to use Generics for this case. The class could look like this :

Now we can simply create our new specific ViewModel like this

to get what we want generically.

 

Another possible scenario would be the following. We know, every ViewModel contains a Collection of Models, all inheriting from a class called ModelBase. we could extend out code the following way:

or, the better way, we could extend our Generic header to be type safe.

Defining a Class by

Like always, if we talk about inheritance, you should avoid to go too far with that. I implemented a Framework I use for rapid prototyping where a lot of things are done in the base-class via reflection, but in a productive environment its not always what you want. Plan your development as precise as possible.

  • What do you want to be individually implemented by each ViewModel ?
  • When is it a good thing to implement it in the Base-Class ?
  • How confusing is you inheritance for other developers ?

 

Good Luck 😮