I'm currently trying to create a small application using the MVVM pattern. However, I do not know how to properly complete the aggregated model classes in my ViewModel. From the fact that little is known about MVVM, you should not show models in your ViewModel as properties, otherwise you can directly bind to the model from your view. So it seems to me that I should wrap the nested model in another ViewModel, but this poses some problems while synchronizing the Model and ViewModel.
So how do you do this efficiently?
I will give a brief example. Suppose I have the following model classes:
public class Bar { public string Name { get; set; } } public class Foo { public Bar NestedBar { get; set; } }
Now I create two ViewModel classes respectively, wrapping Models, but running into problems with FooViewModel:
public class BarViewModel { private Bar _bar; public string Name { get { return _bar.Name; } set { _bar.Name = value; } } } public class FooViewModel { private Foo _foo; public BarViewModel Bar { get { return ???; } set { ??? = value; } } }
Now, what should I do with the FooViewModel Bar property? For get to work, I need to return an instance of BarViewModel. Create a new field of this type in FooViewModel and just wrap the _foo.NestedBar object? Changes to the properties of this field should propagate to the base instance of Bar, right?
What if I need to assign another instance of BarViewModel to this property, for example:
foo.Bar = new BarViewModel();
Now this will not apply to the model, which still stores the old instance of the Bar type. I need to create a new Bar object based on the new BarViewModel and comprehend it on _foo, but how do you do it elegantly? This is pretty trivial in this example, but if Bar is much more complicated with many properties, it will gain a lot ... not to mention that it will be very error prone if you forget to set one of the properties.