user1088858
user1088858

Reputation: 123

Resolve ViewModels for collection of (differently typed) Models

I'm a little confused about the MVVM pattern which i'm combining with PRISM. In short: I'm trying to create views and viewmodels based on existing models which are generated by a separate service. The service doesn't and should not know anything about the views and/or view models. This service creates models of different types, for simplicity lets call them SquareModel and CircleModel. These types all share the same abstract BaseModel. Suppose the service generates a list of type BaseModel, with both Square and Circle Models. The question now is how I translate those Models into corresponding ViewModels and put them in a new list. Each type should get it's own view model; so:

This is because both models expose different properties which I want to bind to using the ViewModel. Also how do I combine those two ViewModel types into a single list to present to my view?

The view contains a listbox which, depending on the viewmodel type loads the appropriate datatemplate.

To make things more clear I put together sample code shown below to show what i've done. The first approach is via a switch on type, the second approach uses ExportFactory of MEF 2.0. Both are failing, the reason why is in the code. I really appreciate any help!

/*
 * Models (these are generated by a service, the service doesn't and should not now about views or view models)
 * 
 * 
 */

abstract class BaseModel { }

class SquareModel : BaseModel { }

class CircleModel : BaseModel { }


/*
 *  View Models
 * 
 * 
 */

abstract class BaseViewModel<TModel> // : INOtificationPropertyChanged, etc
{
    protected TModel Model;

    public void SetModel(TModel model)
    {
        Model = model;
        OnChangeModel();
    }

    protected virtual void OnChangeModel()
    {
        // Assignment of base properties here, based on Model
    }

    // Declarate some base properties here
}

[Export(typeof(BaseViewModel<BaseModel>))]
[TypeMetadata(Type = "CircleViewModel")]
class CircleViewModel : BaseViewModel<CircleModel>
{
    protected override void OnChangeModel()
    {
        // Assignment of circle specific properties here, based on Model
    }

    // Declarate some circle specific properties here
}

[Export(typeof(BaseViewModel<BaseModel>))]
[TypeMetadata(Type = "SquareViewModel")]
class SquareViewModel : BaseViewModel<SquareModel>
{
    protected override void OnChangeModel()
    {
        // Assignment of square specific properties here, based on Model
    }

    // Declarate some square specific properties here
}

class Program
{
    [ImportMany]
    protected IEnumerable<ExportFactory<BaseViewModel<BaseModel>, ITypeMetadata>> Factories { get; set; }

    public BaseViewModel<BaseModel> Create(string viewModelType)
    {
        var factory = (from f in Factories where f.Metadata.Type.Equals(viewModelType) select f).First();

        // Factory is able to create View Models of type viewModelType using CreateExport() function
        var vm = factory.CreateExport().Value;

        return vm;
        // Same error as with solution A
        // cannot convert from 'ConsoleApplication1.SquareViewModel' to 'ConsoleApplication1.BaseViewModel<ConsoleApplication1.BaseModel>'
        // This error is actually displayed in ExportFactory context, but it means the same
    }

    public BaseViewModel<BaseModel> CreateFrom(Type type)
    {
        var vmTypeName = type.Name + "ViewModel";
        return Create(vmTypeName);
    }

    public BaseViewModel<BaseModel> CreateVMUsingExportFactory(BaseModel model)
    {
        var vm = CreateFrom(model.GetType());
        vm.SetModel(model);
        return vm;
    }

    public void DoStuff()
    {
        // Suppose service gives me this
        var serviceOutput = new List<BaseModel>
                                {
                                    new SquareModel(),
                                    new CircleModel(),
                                    new CircleModel(),
                                    new SquareModel(),
                                    new CircleModel(),
                                    new SquareModel(),
                                    new SquareModel()
                                    // may be longer but not the point
                                };

        // viewModelCollection is bound to a listbox, by using datatemplates everthing is nicely placed on the canvas; no problem there
        // Actually this is a ObserveableCollection
        List<BaseViewModel<BaseModel>> viewModelCollection = new List<BaseViewModel<BaseModel>>();


        //
        // What to do here?
        //

        //
        // A. Switch-on-type
        foreach (var model in serviceOutput)
        {
            // Note there are beter implementations of this, using dicationaries and delegates, main goal of that is to not break when refactoring;
            switch (model.GetType().Name)
            {
                case "SquareModel":
                    SquareViewModel vm = new SquareViewModel();
                    vm.SetModel((SquareModel)model); // another cast..... :(
                    viewModelCollection.Add(vm);
                    // Error: 
                    // cannot convert from 'ConsoleApplication1.SquareViewModel' to 'ConsoleApplication1.BaseViewModel<ConsoleApplication1.BaseModel>'

                    break;

                case "CircleModel":
                    // same
                    break;
            }
        }

        // B. MEF ExportFactory<>
        //
        foreach (var model in serviceOutput)
        {
            var vm = CreateVMUsingExportFactory(model);
            viewModelCollection.Add(vm);
        }

        // C. Something else?!
        //
        // Please help ;-).
    }

a

Upvotes: 0

Views: 286

Answers (1)

Anton
Anton

Reputation: 7719

the xaml binding is very forgiving with the object type, you can use object instead of defining a type

baring any problems with your datatemplate code(which off the top of my head shouldnt be a problem), use the following

List<object> viewModelCollection = new List<object>(serviceOutput.Select(model=> CreateVMUsingExportFactory(model) as object));

the above uses linq and lambda to create a list of objects.

Upvotes: 2

Related Questions