In a wpf application, a Model object is created either from scratch or deserialized from some .xml file. To create a connection to the ViewModel, the following method (on the Model!) is used by the application:

class Model
{
    public override UserControl View
    {
        get
        {
            if (_view == null)
            {
                ViewModel viewModel = new ViewModel(this);
                _view = new View();
                _view.DataContext = viewModel;
            }
            return _view;
        }
    }
}

So far, so not mvvm. The Model should not know (=have a direct reference to) the ViewModel, let alone the View.

mvvm diagram

Breaking the pattern this way served as a convenient shortcut, but is starting to take a toll. I'd like to get rid of this method to separate the concerns properly as intended by the pattern.

But how would I do that? The functionality of the method in itself looks alright mmvm-wise. If I'd take it out of Model and place it in the application, it looks like proper mvvm-ish code that wires up the components:

ViewModel viewModel = new ViewModel(new Model);
_view = new View();
_view.DataContext = viewModel;

But I cannot do that, because I do not know what Model class I'm dealing with, when looking at the problem from the application point of view, because any one of several Model classes might get instantiated or deserialized. In some sense, the Model knows best what ViewModel to use (hence the current implementation), but this is exactly the dependency that I'm trying to avoid.

How to build the parts of the mvvm pattern "against the grain" of the dependencies of the pattern? That is, going from Model to View(Model)and not the other way round.

  • A simple solution might be to define a data structure in the application (e.g. a Dictionary) to associate a specific ViewModel that should be used with a specific Model, but this means maintainance when adding more classes, making mistakes doing so, etc.
  • One could also build that association with reflection introducing a strict naming scheme like every FooModel will go together with a FooModelView, which would be an improvement, but is still prone to breaking.
  • Or use some dependency injector thingy (e.g. mef) to automate the process of finding the pieces that belong together. But again, the dependencies seem to go the wrong way: The ViewModel might [Import] an IModel that the Model could then [export], but the Model (=the dependency) is created first, so I'd be looking for imports that would be satisfied with a given export and not the other way round. While such tools would help to split the concerns across even different assemblies (which is good and a goal, too), they don't solve the underlying problem that I don't know how to start this separation in the first place, which isn't their intended purpose anyway. If I swap import and export, my guess is that I'd end up with what I started with.

Are there any better solutions than building an association between the two (either by hardcoding it or reflection) in the application?


can you explain how and why each ViewModel doesn't already know the proper Model class to instantiate and the proper Model methods to call? Isn't that one of the primary reasons for having ViewModel classes in the first place?

Every ViewModel knows the proper Model class. I'm sorry if that wasn't clear from the text. In the code example, the Model is passed to the constructor of the ViewModel. The ViewModel does not instantiate the Model object as this object might be constructed elsewhere (e.g. it could come from a deserialisation process). That is indeed the primary reason for it to exist.

The problem is deciding what ViewModel to create, so that the Model (of a type that is decided at runtime) at hand can be passed to it.

Assuming you intend to use some form of IoC to solve this problem, couldn't you simply use the configuration of the DI container to identify the required model, or use a Service Locator?

Can you also further clarify the phrase, "Breaking the pattern this way served as a convenient shortcut, but is starting to take a toll"?

Given that the Model itself ensured that the right ViewModel (and View) would be instantiated, the returned value could be carelessly added to the screen. The correct wiring of the components happened in the method seen in the first code example. So much for the convenience of being able to "display" a Model. The toll to be paied is that Model would use and therefore reference View and ViewModel, which are classes that depend on GUI libraries, which the Model should not depend on.

or, to be blunt: Why does this console application need 5 dlls for graphical user interface components?

couldn't you simply use the configuration of the DI container to identify the required model, or use a Service Locator?

I guess the mentioned datastructure that associates ViewModel with Model is a (poor man's) Service Locator. I'm new to that pattern, but from a first glance that seems to be the case. Using the expected type of the ViewModels to build it is something I haven't thought about. (I'm thinking and not or regarding your question) As far as that approach goes, I'd take your suggestion as an answer. I was however hoping for a solution that's a little less DIY-ish. Seeing how binding does a lot of thing automatically, I'm somewhat surprised to find that going the opposite direction (that is, having a Model to begin with) requires such manual dependency management. But then maybe this is what it takes.

  • So it sounds like your core problem is that you cannot identify the Model that needs to be instantiated. Assuming you intend to use some form of IoC to solve this problem, couldn't you simply use the configuration of the DI container to identify the required model, or use a Service Locator? – Robert Harvey Oct 10 '17 at 17:07
  • Also, can you explain how and why each ViewModel doesn't already know the proper Model class to instantiate and the proper Model methods to call? Isn't that one of the primary reasons for having ViewModel classes in the first place? Can you also further clarify the phrase, "Breaking the pattern this way served as a convenient shortcut, but is starting to take a toll"? – Robert Harvey Oct 10 '17 at 17:24
  • @RobertHarvey I hope I could provide some more insight with my edit. – surface Oct 10 '17 at 17:51
  • Seeing how binding does a lot of thing automatically, I'm somewhat surprised to find that going the opposite direction (that is, having a Model to begin with) requires such manual dependency management. -- That's because MVVM expects the dependency chain to proceed in the opposite direction. Your requirement expects the Model to have knowledge of the ViewModel, an expectation that is not assumed in traditional MVVM. There wouldn't be any default mechanisms for an operation that is not an assumed part of the paradigm. – Robert Harvey Oct 10 '17 at 18:00
  • I suggest you have a look at the latest version of Prism. It's designed specifically to embody patterns and practices that enable modular, decoupled WPF applications. Maybe it has some solutions you have overlooked. – Robert Harvey Oct 10 '17 at 18:05
up vote 1 down vote accepted

Here are my suggestions:

Suggestion 1

You could try to use extension methods in order to separate concerns and in the end, perform exactly what you need (models that know their respective viewmodels):

using System;
using System.Collections.Generic;

namespace Yay
{
    public class BaseModel
    {
        public bool CommonStuff { get; set; }
    }

    public class FromScratchModel : BaseModel
    {
        public string A { get; set; }
        public string B { get; set; }

    }

    public class DeserializedModel : BaseModel
    {
        public int C { get; set; }
        public bool D { get; set; }

    }

    public class BaseViewModel
    {
        public override string ToString()
        {
            return "Base View Model!!!!";
        }
    }

    public class ViewModel1 : BaseViewModel
    {
        public override string ToString()
        {
            return "View Model - From Scratch!!!!";
        }
    }

    public class ViewModel2 : BaseViewModel
    {
        public override string ToString()
        {
            return "View Model - Deserialized!!!!";
        }
    }

    static class Extensions
    {

        public static BaseViewModel GetViewModel(this BaseModel model)
        {
            return new BaseViewModel();
        }

        public static BaseViewModel GetViewModel(this FromScratchModel model)
        {
            return new ViewModel1();
        }

        public static BaseViewModel GetViewModel(this DeserializedModel model)
        {
            return new ViewModel2();
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            IList<BaseModel> models = 
                new List<BaseModel> { new BaseModel(), 
                                    new FromScratchModel(), 
                                    new DeserializedModel() };
            foreach (var model in models)
            {
                //Calling model.GetViewModel() will not work here; already tried (it runs, but it will return the BaseViewModel always).
                //But it's possible to call the right method resolved at runtime
                //using dynamic keyword
                BaseViewModel viewModel = Extensions.GetViewModel(model as dynamic);
                Console.WriteLine(viewModel.ToString());
            }

            Console.ReadLine();
        }
    }
}

Suggestion 2

You have different models that can arrive, that are resolved at runtime. In this option I suggest:

  • On your core project (not the UI project), for each type of your model, create a "model loader" class, that will Notify the clients about new models (eg: DeserializedModelLoader; FromScratchModelLoader)
  • On your UI, create one listener for each type of existing model (eg: DeserializedModelListener, FromScratchModelListener);
  • each listener can return a ViewModel ready to be rendered, which will be of the appropriate type, and already contain the Model received;
  • maintain a list of those listeners; for every new Model arrived, you can retrieve the appropriate ViewModel from the listener that received something.
  • A similar solution to this was implemented, but simpler. The method in the question was indeed placed in another class. The matching however is achieved with a strict naming scheme. Again, this has known drawbacks, but it solves the problem. – surface Oct 13 '17 at 8:20

The following is the result of my deliberations during the last two days. The resulting solution is an idea, that also contains some problems I already discovered. I hope for a discussion whether the structure and design of the solution is good and which (anti-)patterns it may realize. Since my ideas originated from this post, I'll post it as an answer here, but I also thought of asking a new question (linking to this one).


Well, we want to achieve that models are completely independent from view models (let alone from views) and still infer to one, if we need one. Let's imagine our models are POCOs:

class Base { /* some properties */ }
class Special : Base { /* more properties */ }
class ExtraSpecial : Special { /* even more properties */ }

Now, we use a simple generic approach as base class for our view models:

abstract class ViewModel<ModelType>
{
    protected ModelType Model;

    public ViewModel(ModelType model)
    {
        this.Model = model;
    }
}

class BaseViewModel : ViewModel<Base> { /* constructor and view model stuff */ }

class SpecialViewModel : ViewModel<Special> { /* constructor and view model stuff */ }

Now our view models know about the type of model, which they have to present to the respective view. The view only knows what to show for which view-model.


Let's get back to the problem in the question. We get a new model (from anywhere, e.g. deserialization) and we know that it is a Base, but we do not know which Base. We could simply use a BaseViewModel, but if it is a Special, we will still at best loose features. We want to check which type of Base our model really is. For a simple case, we might use some if-branches, but that will become ugly soon. Using reflection we could find a view model via the model name, but naming rules (not conventions) are shitty in nine times out of ten. We could build a relation between models and view models ... maybe use a dictionary ... or register them in some kind of service locator ... but wait! We already built a relation via generics, from our view models to the models. Couldn't we just check which view model is capable of handling our model type?

First, we collect all view models ...

HashSet<Type> types = new [] { typeof(BaseViewModel), typeof(SpecialViewModel) };
// or we collect them from some assembly or namespace

Then we extract the model type for each of them:

for (; type != null; type = type.BaseType)
{
    if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(ViewModel<>)))
    {
        return type.GetGenericArguments().Single();
    }
}
return null;

And finally we can check if it matches our target model:

type.IsAssignableFrom(modelTypeTarget)

First problem: If we only check for assignability (instead of equality), we will find multiple possible view models for a model, we need to decide which one to use.

Solution: We calculate an inheritance distance (and minimize it) to determine which view model matches a model the best:

private static uint GetInheritanceDistance(Type type, Type parent)
{
    uint i = 0;
    for (; type != null; type = type.BaseType)
    {
        if (type.Equals(parent))
        {
            return i;
        }
        i++;
    }
    return uint.MaxValue;
}

This way a ExtraSpecial will get a SpecialViewModel assigned, not a BaseViewModel.


Second problem: What happens if we need (or want) multiple view models for one model, e.g. one for showing an entry and the other one for editing?

Solution: We introduce contexts. These contexts can be assigned to view model types via attributes:

[ViewModelContext(Context.View)]
class BaseViewModel : ViewModel<Base> { /* ... */ }
[ViewModelContext(Context.Edit)]
class EditBaseViewModel : ViewModel<Base> { /* ... */ }

Now we only consider those view models that match the context that we need in our specific case.


Just for your information, I implemented the functionality I described above, so I may add a repository link later, but for now I want to know if this may solve the problem described in the question and if it would be considered a good solution.

  • Your solution goes in the direction of what Robert suggested (in the comments), but goes further by trying to solve secondary aspects of the problem. "I hope for a discussion whether the structure and design of the solution is good" I guess Code Review is a good place to ask for that, especially if you have already implemented it (which is a prerequisite for asking a question there) – surface Oct 13 '17 at 8:12

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.