A domain model collection (normally a List or IEnumerable) is delegated to a ViewModel.
Thats means my CustomerViewModel has a order collection of type List or IEnumerable.
No change in the list is recognized by the bound control. But with ObservableCollection it is.
This is a problem in the MVVM design pattern.
How do you cope with it?
UPDATE: Sample of how I do it:
public class SchoolclassViewModel : ViewModelBase
{
private Schoolclass _schoolclass;
private ObservableCollection<PupilViewModel> _pupils = new ObservableCollection<PupilViewModel>();
public SchoolclassViewModel(Schoolclass schoolclass)
{
_schoolclass = schoolclass;
_schoolclass.Pupils = new List<Pupil>();
foreach (var p in schoolclass.Pupils)
Pupils.Add(new PupilViewModel(p));
}
public Schoolclass GetSchoolclass
{
get { return _schoolclass; }
}
public int ID { get; set; }
public string SchoolclassName
{
get { return _schoolclass.SchoolclassName;}
set
{
if(_schoolclass.SchoolclassName != value)
{
_schoolclass.SchoolclassName = value;
this.RaisePropertyChanged("SchoolclassName");
}
}
}
public ObservableCollection<PupilViewModel> Pupils
{
get{ return _pupils;}
set
{
_pupils = value;
this.RaisePropertyChanged("Pupils");
}
}
}
I deal with this by not doing it the way you describe.
If I need to present a Foo object and its related Bar objects in the view, the FooViewModel will generally implement a Bars property of type ObservableCollection<BarViewModel>.
Note that this is irrespective of whether or not the underlying Foo class has a Bars property of type IEnumerable<Bar>. The Foo class might not. The application might not even need to be able to iterate over all of the Bar objects for a Foo, except in the UI.
Edit
When my view is a simple representation of the application's object model, I pretty much do things as you do in your sample. The code in my constructor is generally a bit more compact:
_Bars = new ObservableCollection<BarViewModel>(
_Foo.Bars.Select(x => new BarViewModel(x)));
but it's essentially the same thing.
But this assumes that Foo actually exposes a Bars property. It might not. Or maybe only some Bar objects should appear in the view. Or maybe they should appear intermingled with other objects, and the FooViewModel should expose a CompositeCollection of some kind.
The point I'm making is that the view model is a model of the view. This doesn't necessarily have a direct correspondence to the underlying object model.
To pick a simple example: My program may give the user a way of putting items into five different categories by dragging and dropping them into five different ListBox controls. Ultimately, doing this sets a Category property on the Item object. My view model is going to have a collection of CategoryViewModel objects, each with a property of type ObservableCollection<ItemViewModel>, so that dragging items back and forth between collections is simple to implement.
The thing is, there may not even be a Category class in the application's object model, let alone a collection of Category objects. Item.Category might just be a property of type string. The CategoryViewModel isn't mirroring the application's object model. It only exists to support the view in the UI.
Ok, I'll go ahead and add my thoughts as an answer instead of in the comments. :)
I think the bottom line is that this is just the reality of the way WPF and databinding work. In order for two-way databinding to operate, collections need a means of notifying controls that are bound to them, and the standard lists and collections used in most domain objects don't/won't/shouldn't support this. As I mentioned in a comment, being required to implement INotifyPropertyChanged for non-collection properties is another requirement that may not be met by a standard domain object.
Domain objects are not intended to to be viewmodels, and for this reason you may find that you need to map back and forth between the two types of objects. This is not dissimilar to having to map back and forth between domain objects and data access objects. Each type of object has a different function in the system, and each should be specifically designed to support their own role in the system.
All that said, Agies's idea of using AOP to automatically generate proxy classes is very interesting, and something I intend to look into.
What I do is instead of using ObservableCollection in my domain model is use my own collection type that implements the INotifyCollectionChanged interface amongst other useful standard and custom interfaces. My way of thinking is that much like Rockford Lhotka suggests in his book that change notification is useful in to more than just a presentation layer since other business objects within the domain layer often need some sort of notification when state changes in another object.
With this methodology you could create your own collection type that still has the benefits of change notification and as well as what ever custom behaviors you need. The base class for your collection could be implemented as purely infrastructure code and then a subclass could be created that could contain business logic using the subtype layering techinque used in this book. So in the end you could have a collection that can wrap types of IEnumerable<> and provide the change notification stuff your looking for as well for both your domain model and presentation code.
Related
what I think I face is a problem of design - one I assume has been solved many times by many people since it seems like it would be very common.
I'm using WPF with XAML and a simple MVVM approach, for the record.
My intention is to create a TreeView, using the MVVM design pattern in WPF.
I have a data model which contains two classes: Scene and Character. Each Scene contains many Characters.
I have created a CharacterViewModel, which is fairly simple (and works fine). Naturally this wraps around the existing Character class.
The Scene class is where I'm getting confused. As I understand it, the SceneViewModel should wrap around the Scene class, just as the CharacterViewModel did for the Character class. But the difference is that Scene contains a list of Characters and thus adds exta complications.
The two options seem to be as follows:
Option 1: Scene contains List of Character and so SceneViewModel also will have that as part of it.
Option 2: Scene contains List of CharacterViewModel and so SceneViewModel will also have that as part of it.
I'm not sure which one to go for to be honest. I suspect it's the second (and this tutorial seems to agree (example 6 is the heading for the section I'm referring to). The first option seems like it would make things really weird (and also why created the CharacterViewModel at all?) but the second seems strange because it seems to muddy the waters regarding what should be in the model part of the program and what should be in the view model part of the program.
I hope I've explained my problem and I also hope someone can offer some help.
Thanks.
Let me first address this statement:
...the SceneViewModel should wrap around the Scene class, just as the CharacterViewModel did for the Character class.
This isn't exactly true. View model should be created for each view. There may be a one-to-one with your model classes, but that isn't a strict part of the MVVM idea. One view may need to present data from multiple "root" model elements (model elements that don't have an explicit relationship like the parent-child relationship in your application), or you may need to have multiple views for a single model element. And to elaborate further, each view model should ideally be isolated from the view technology as much as possible (i.e. a single view model is sufficient to create a WinForms view or a WPF view or an HTML view, etc).
For example, you may have a view that displays data from your Scene class. That view may also display some data for each Character in your Scene. The user may be able to click on a Character and open a view just for that Character (e.g. a popup). In this case, there may be separate view models to represent the Character in the root view and the popup. I tend to name my view model classes according to the root of the view. For an application like yours, I would have something like SceneViewModel and SceneCharacterViewModel (or SceneViewModel_Character, or CharacterInSceneViewModel -- any of these names conveys that the class is for representing a Character in a view for a Scene). This would differentiate that view model from the popup view (which would be Character-centric and would be named something like CharacterViewModel (or even CharacterDialogViewModel or CharacterPopupViewModel or CharacterEditorViewModel).
Keeping collections in sync between the model and view model is annoying but often necessary. Not always necessary, mind you -- there will be cases in which you'll find there are no additional view-model features that you need to add to a model, so it's perfectly acceptable for the view to reference the model directly in this case.
An example of keeping a model collection and view model collection in sync: Suppose your root SceneView has a button for each Character. That button will display a popup for the Character. Suppose further that the Character popup doesn't have a similar button because then it would allow the popup to open another popup (etc). You may want to use an ICommand implementation so that you can just bind the button to the command. It's definitely not appropriate for the ICommand instance to be in the model (even though the command may call a public method on the model). The appropriate place for this would be in the view model for the Character in the Scene view (not the view model for the Character in the popup). For every Character in the model, you would need to create a view model that references the Character and stores additional view-model stuff (the ICommand object).
This means that, as Characters are added/removed from the Scene, you need to create view models specifically for those Characters within the Scene view model. I would typically do this:
At construction time (or whatever time the view model initially receives the model), create a view model for each child object. Put those view models into a public property with a type of something like ReadOnlyCollection<SceneCharacterViewModel>. Your view will bind to that collection.
As child objects are added to the model (either internally or through a public method on the model), the model should notify the view model in an appropriate way. Since the model shouldn't have a direct reference to the view model (not even through an interface -- a model should be completely functional even in a non-UI context, in which there is no view model), the most appropriate way is to use events. You can do this a couple of ways:
Expose events from your model like CharacterAdded, CharacterRemoved or even CharactersUpdated (the last of these would be able to communicate either an add or a remove using a single event)
ObservableCollections (or ReadOnlyObservableCollections), which are most commonly used in view models, can also be used in models, in which case all the events are already available to you. The downside to this is that processing the events off of these collection types isn't the easiest thing.
A third option that is totally different: If your view model or command instance is directly invoking a method like sceneModel.AddCharacter(newCharacterModel), then you can just update your view model immediately after this line without needing any events. I often find myself starting this way because it's simple, but I almost always end up using one of the previous two techniques instead, as those techniques allow the model to notify the view model even in cases where the update is happening internally (e.g., in response to a timed event or asynchronous operation that is controlled by the model).
All of that being said, here's what a "pure" MVVM architecture would look like for your application. Purity can come at the expense of simplicity, so sometimes it's better to take some shortcuts here and there. One common shortcut: In WPF, it's often easier just to put all of your child widget content in the ItemTemplate of the ItemsControl that is being used to diplay your children, rather than creating a separate UserControl for the children.
I guess from your explanation Scene is the Model and SceneViewModel would wrap additional view related functionality to your model in the view model. Same applies for CharacterViewModel.
Whatever your view needs to display you would have a SceneViewModel with a list of CharacterViewodel or vice versa. Or like mentioned your could build up a tree structure with your ViewModels.
My personal view of things is, it is important to stay in the ViewModel universe. So when your construct a view model you would inject your model via a service and build up your ViewModel and only have lists with view models. You would need to do some mapping but there are useful frameworks like automapper, etc already available. But remember there are no hard rules with MVVM.
I didn't understand your choices, However, I think you just need one View Model and it should contain an ObservableCollection of the Scenes. I name it SceneViewModel:
public class SceneViewModel
{
public SceneViewModel()
{
Scene m1 = new Scene() { Name = "Scene1", Characters = new ObservableCollection<Character>() { new Character() { Name="C1" }, new Character() { Name = "C2" } } };
Scene m2 = new Scene() { Name = "Scene2", Characters = new ObservableCollection<Character>() { new Character() { Name = "D1" }, new Character() { Name = "D2" } } };
Scene m3 = new Scene() { Name = "Scene3", Characters = new ObservableCollection<Character>() { new Character() { Name = "R1" }, new Character() { Name = "R2" } } };
_scenes = new ObservableCollection<Scene>() { m1, m2, m3 };
}
ObservableCollection<Scene> _scenes;
public ObservableCollection<Scene> Scenes { get { return _scenes; } set { _scenes = value; } }
}
Scene will have an ObservableCollection of Characters
public class Scene : INotifyPropertyChanged
{
ObservableCollection<Character> _characters;
public ObservableCollection<Character> Characters { get { return _characters; } set { _characters = value; RaisePropertyChanged("Characters"); } }
string _name;
public string Name { get { return _name; } set { _name = value; RaisePropertyChanged("Name"); } }
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(string propname)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propname));
}
}
and at last, Character:
public class Character : INotifyPropertyChanged
{
string _name;
public string Name { get { return _name; } set { _name = value; RaisePropertyChanged("Name"); } }
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(string propname)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propname));
}
}
View
<TreeView DataContext="{Binding}" ItemsSource="{Binding Scenes}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Characters}">
<TextBlock Text="{Binding Path=Name}"></TextBlock>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"></TextBlock>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
public MainWindow()
{
InitializeComponent();
DataContext = new SceneViewModel();
}
I think this is a rather basic question, but I haven't been able to find an answer to this.
I have the following scenario:
Without using any form of EntityFrameWork I have a PersonViewModel and a PersonDetailsViewModel, which inherits from the PersonViewModel. In my PersonView I display a collection of PersonViewModels in a grid. I have properties like Name, DateOfBirth etc, as columns. When I double click on a person a PersonDetailView pops up which is bound to a PersonDetailsViewModel. In this View there is extra information shown about the person (Gender, SocialSecurity number etc.). The user I allowed to edit all properties.
Now I wonder what the best/common approach is to make sure that the PersonViewModel gets updated with the values that have been editted in the PersonDetailsViewModel.
I can think of several options. For starters I could opt for not using different ViewModels, but instead use PersonDetailViewModels to show in the grid, but the downside to that is that I would need to retrieve a lot of unnecessary data per ViewModel.
I can also synchronise the corresponding properties after the PersonDetailsView closes.
The third option I can think of is that instead of inheriting from the PersonView I will include a property in PersonDetailsView that is of the type PersonView and expose it's properties and use it for binding in the PersonDetailsView. All other extra properties in PersonDetailsViewModel will then be retrieved in it's constructor.
In my experience, the best way to update view models who share the same data is to use the Mediator pattern to send a notification message that the data has updated.
In order to have a good object oriented design we have to create lots
of classes interacting one with each other. If certain principles are
not applied the final framework will end in a total mess where each
object relies on many other objects in order to run. In order to avoid
tight coupled frameworks, we need a mechanism to facilitate the
interaction between objects in a manner in that objects are not aware
of the existence of other objects.
Source http://www.oodesign.com/mediator-pattern.html
It is syntactically important to your design that the notification says what has happened (the data was updated) and not what should happen (data gets reloaded) because that response may not stay the same as the system evolves.
Often, common MVVM libraries have Mediator implementations in them. For example, Prism's EventAggregator.
in Addition to Sheridans answer. i would expose the Detail as a property of type PersonDetailsViewModel
public class PersonViewModel
{
public PersonDetailsViewModel Detail {get;set;}
}
then your xaml looks simply like that
<TextBlock Text="{Binding Detail.Gender}"/>
EDIT1: in addition to the comments above
i would not do any inheritence (thats what user1087702 wrote in his question). i would simply create 2 classes: PersonVM and PersonVMDetail. And if the request is, to show Details from my person object, why in hell shouldn't i just create a public Property in my PersonVM class of type PersonVMDetail - to fullfill this request?
The simplest way to achieve your requirements would be to add a constructor to your PersonViewModel class that takes a PersonDetailsViewModel instance and updates its common properties:
public PersonViewModel(PersonDetailsViewModel personDetailsViewModel)
{
Name = personDetailsViewModel.Name;
...
DateOfBirth = personDetailsViewModel.DateOfBirth;
}
...
PersonViewModel = new PersonViewModel(PersonDetailsViewModel);
Of course, this doesn't have to be in the constructor... it could just as easily be a method in the PersonViewModel class, or even a helper method in a separate Factory Pattern class, it's up to you.
In the model of my application I have a list of "parents" each referecing a list of "children" (e.g. a list of footballteams each containing a list of players).
I visualize this list in a tree view. I created a viewmodel-class for the tree and a viewmodel-class for a footballteam (let's call it "footballteamViewModel"). The class for the tree holds an ObservableCollection with footballteamViewModel-items. The items-source for the tree is this ObservableCollection. During initialization, I create for every footballteam in the model a corresponding footballteamViewModel object and add it to the ObservableCollection.
The thing is, that the list of footballteams in my model can be changed from outside of the tree and I want the tree to be updated. So if someone removes a footballteam from my list in the model, I would have to remove the corresponding item in my ObservableCollection of footballteamViewModel-items.
I cannot bind the list of footballteams from the model directly to the view. So I have to update my ObservableCollection in the ViewModel somehow, every time the collection in the model is changed.
My way to handle this is to use an ObservableCollection in the model and register to the collectionChanged-event in the ViewModel, so that I update my ViewModel (the Observable Collection of footballteamViewModel objects) whenever the model-collection is changed. But this does not feel "right". Is there a better way?
While typing this I found another post which describes exactly the same problem: WPF/MVVM: Delegating a domain Model collection to a ViewModel. The answers there encourage me that the way I'm solving this problem is not totally wrong but still I wonder if there is another method.
EDIT: From the first answers that you provided I assume that there is no definite answer to my question. They were all helpful, so it's worth reading them all. I only mark the answer with the reference to the Bindable Linq/Continous Linq/Optics frameworks, because I think it will help other who stumble over my question most.
This is one of the more nasty spots of MVVM.
One thing I have done a while ago is create a ViewModelCollection<T> which inherits ObservableCollection<T> and has modificator methods (Add, Remove), that perform operations on both collections,like so:
public interface IViewModel<T>
{
T WrappedModel { get; }
}
public class ViewModelCollection<T,M> : ObservableCollection<T,M> where T : IViewModel<M>
{
private IList<M> _baseCollection;
public ViewModelCollection(IList<T> baseCollection)
{
_baseCollection = baseCollection;
}
public override void Add(T objectToAdd)
{
IViewModel<M> vm = objectToAdd as IViewModel<M>;
if (vm != null)
{
this.Add(objectToAdd);
_baseCollection.Add(vm.WrappedModel);
}
}
public override void Remove(T objectToRemove)
{
IViewModel<M> vm = objectToRemoveas IViewModel<M>;
if (vm != null)
{
this.Remove(objectToRemove);
_baseCollection.Remove(vm.WrappedModel);
}
}
}
By now I don't do this at all, I just work with Castle Proxies that add the INotifyPropertyChanged functionality to my models - saves a lot of boilerplate code!
Please note, I haven't tested the code, just typed it down from memory.
You said that you cannot bind the model collection directly to the view (which means that the viewmodel needs to make its own ObservableCollection with a copy of what the model collection contains), and additionally that the view needs to be updated live when the model collection changes (which means that the model needs to inform the viewmodel of such changes, and the viewmodel needs to update its internal copy).
All of this doesn't leave much wiggle room really. One variation that might be interesting is making the model's collection a read/write IEnumerable, in which case consumers of the model would be forced to swap it with a new instance whenever they need to modify the collection. In return, the viewmodel's "stay in sync" code can be simplified and sync can be triggered through INotifyPropertyChanged on the collection property.
Your solution is not wrong at all, but there are some libraries that could help you implement it easier, like BindableLinq, ContinuousLinq or Obtics. You have a discusion about them here. Sadly, none of them seem to be under further development.
My personal experience with Clinq is excellent and i still use it, should work for your case.
Late, but may helps other ppl...
read this excellent 3 Part blog post series about this topic.
Part 3 is about collections and shows some solutions - helps me a lot
MVVM: To Wrap or Not to Wrap? How much should the ViewModel wrap the Model?
I'm having trouble understanding how to apply the MVVM pattern when Lists/Collections are involved.
Say the MainModel has a few properties and methods, as well as a list that contains other DetailModel objects. The DetailModel objects can be added, removed, or re-ordered.
The MainView will show a few controls related the the root model, and have a ListBox populated from the list. Each item will have it's own sub-view via a DetailModelView UserControl.
Finally, there is a MainViewModel. This has properties backed by the MainModel's properties and methods, bound to the Main View, with change notification keeping everything in sync. (Up to this point, I am comfortable with the pattern - more stating this in case there is something fundamental I am missing...)
When it comes to handling the list, I get confused. I have come across several examples where the MainViewModel simply exposes the list of DetailModels to the view, and the DetailModelViews are bound directly to the models. This functions, but is problematic. It does not consistently following the pattern (no DetailViewModel exists), and it drives me to include some UI-related code in my detail models. It seems clear to me that the MainViewModel should expose a list of DetailViewModels for the UI to bind, but I am stuck on how to implement such a thing!
How should manage the two lists (DetailModels and DetailViewModels)? I am really confused as where I initially populate the DetailViewModel list, and how I should handle adding, removing, or changing the order of the items to keep them synchronized!
Usually Models are nothing more than data objects. They shouldn't contain any code to do things like add/remove items from a list. This is the ViewModel's job.
In your case, I would create a MainViewModel that has the following properties:
ObservableCollection<DetailViewModel> Details
ICommand AddDetailCommand
ICommand RemoveDetailCommand
If your MainModel class is a data object, you can either expose it, or it's properties from the MainViewModel as well. Exposing it's Properties is the "MVVM purist" approach, while exposing the entire Model is sometimes more practical.
Your MainViewModel is in charge of creating the initial list of DetailViewModels, and it is in charge of Adding/Removing these items as well. For example, in the PropertyChanged event for the MainViewModel.MainModel property, it might rebuild the MainViewModel.Details collection, and the CollectionChanged event for the MainViewModel.Details property would update MainViewModel.MainModel.Details
You are right to have a separate DetailModels list and DetailViewModels list. The DetailViewModels list should be a property of type ObservableCollection<DetailViewModel>. You can populate the observable list when you set the Model (or at construction time, if you pass the model into the constructor of your ViewModel.)
private ObservableCollection<DetailViewModel> m_details;
public IEnumerable<DetailViewModel> Details
{
get { return m_details; }
}
You can the subscribe to m_details.CollectionChanged. This is where you can handle re-ordering the contents of the list in the Model.
I hope this helps.
In my experience, the only time you get away with exposing model objects to the view is if you're doing simple read-only presentation, e.g. displaying a string property in a ComboBox. If there's any kind of actual UI involving the object (especially one involving two-way data binding), a view model is needed.
Typically, a master VM's constructor will look like this:
public MasterViewModel(MasterModel m)
{
_Model = m;
_Detail = new ObservableCollection<DetailViewModel>(m.Detail);
}
where MasterModel.Detail is a collection of DetailModel objects, and _Detail is a backing field for a Detail property that's exposed to the view.
As far as adding, removing, and reordering items in this list is concerned, in the UI at least this will be done through commands on the MasterViewModel, which must manipulate both MasterModel.Detail and MasterViewModel.Detail. That's a bit of a pain, but unless you want to repopulate MasterViewModel.Detail after every change to MasterModel.Detail, it's really unavoidable.
On the other hand, if you've been wondering "why would I ever need to write unit tests for view models?", now you know.
Here is an answer that I think addresses this issue very nicely using an ObservableViewModelCollection<TViewModel, TModel>
It's nice and lazy. It takes an ObservableCollection and a ViewModelFactory in the ctor. I like it because it keeps state at the model layer where it belongs. User operations on the GUI can invoke commands at the VM which manipulate the M via public methods on the M. Any resulting changes at the M layer will be automatically handled by the class in this link.
https://stackoverflow.com/q/2177659/456490
Note my comment regarding SL vs. WPF
In our application we have many Model objects that have hundreds of properties.
For every property on the model:
public string SubscriptionKind { get; set; }
...100x...
we had to make an INotifyPropertyChanged-enabled property on the ViewModel:
#region ViewModelProperty: SubscriptionKind
private int _subscriptionKind;
public int SubscriptionKind
{
get
{
return _subscriptionKind;
}
set
{
_subscriptionKind = value;
OnPropertyChanged("SubscriptionKind");
}
}
#endregion
...100x...
which meant that when our View sent the Save event, we had to remap all these values of the view model back into the model:
customer.SubscriptionKind = this.SubscriptionKind
...100x...
This became tedious and time-consuming as the models kept changing and we had to map all changes up into the ViewModels.
After awhile we realized that it would be more straight-forward to just connect the DataContext of the View directly to the Model which enables us to bind the XAML elements directly to the Model object properties so that the save event would simply save the object without any mapping whatsoever.
What we lost in this move is:
the ability via UpdateSourceTrigger=PropertyChanged to do fine-grained validation and manipulation in the ViewModel Property Setters, which I really liked: this we don't have anymore since any change in XAML simple changes the dumb property on the Model
the ability (in the future) to create mock views which test our viewmodel's UI logic in a novel way, e.g. "if property SubscriptionKind is set to "Yearly" then (1) change discount to 10%, (2) run "congratulations animation", and (3) make order button more prominent.
Both of these approaches have obvious advantages, e.g. the first way "View-direct-to-Model" approach especially when combined with LINQ-to-SQL is pragmatic and enables you to produce useful software fast, and as long as you use {Binding...} instead of x:Name you still have the ability to "hand off your views to a Blend Designer".
On the other hand, although MVVM requires you to maintain tedious mapping of Model to ViewModel, it gives you powerful validation and testing advantages that the first approach doesn't have.
How have you been able to combine the advantages of these two approaches in your projects?
Since your ViewModel has access to the model, you can also just directly wrap the model's properties:
#region ViewModelProperty: SubscriptionKindprivate
// int _subscriptionKind; - Use the model directly
public int SubscriptionKind
{
get
{
return this.Model.SubscriptionKind;
}
set
{
if (this.Model.SubscriptionKind != value)
{
this.Model.SubscriptionKind = value;
OnPropertyChanged("SubscriptionKind");
}
}
}
#endregion
The advantage here is you can keep your validation in place in the ViewModel if you wish, and have more control over how it's set back to your model, but there is less duplication in place.
Why not use a mapping tool like AutoMapper? It's speedy and you don't have to write all of that mapping code:
Mapper.CreateMap<MyModel, MyViewModel>();
MyViewModel vm = Mapper.Map(myModelInstance);
Really easy and now you get the best of both worlds.
Automapper uses a technique that generates assemblies on the fly to do the mapping. This makes it execute just as fast as if you had written all of that tedious mapping code, but you don't have to.
Since my model objects are business objects, not directly related to the datamodel, I use them directly in the ViewModel.
The first mapping (datamodel to business object model) and the creation of properties are generated by a code generator.
I used a t4 Generator class to create my ViewModels from XAML not sure if this would help your situation.