C# generics with MVVM, pulling the T out of <T>

Posted by bufferz on Stack Overflow See other posts from Stack Overflow or by bufferz
Published on 2010-04-23T13:30:27Z Indexed on 2010/04/23 13:33 UTC
Read the original article Hit count: 183

Filed under:
|
|
|

My Model is a generic class that contains a (for example) Value property which can be int, float, string, bool, etc. So naturally this class is represented something like Model<T>. For the sake of collections Model<T> implements the interface IModel, although IModel is itself empty of any content.

My ViewModel contains and instance of Model<T> and it is passed in through ViewModel's constructor. I still want to know what T is in ViewModel, so when I expose Model to the View I know the datatype of Model's buried Value property. The class for ViewModel ends up looking like the following:

class ViewModel<T>
{
   private Model<T> _model;

   public ViewModel(Model<T> model) { ....blah.... }

   public T ModelsValue {get; set; }

}

This works fine, but is limited. So now I need to expose a collection of IModels with varying Ts to my View, so I'm trying to set up an ObservableCollection of new ViewModel<T>s to a changing list of IModels. The problem is, I can't figure out how to get T from Model<T> from IModel to construct ViewModel<T>(Model<T>) at runtime.

In the VS2010 debugger I can mouseover any IModel object and see its full Model<int> for example at runtime so I know the data is in there.

Any ideas?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics