Good examples of MVVM Template - wpf

I am currently working with the Microsoft MVVM template and find the lack of detailed examples frustrating. The included ContactBook example shows very little Command handling and the only other example I've found is from an MSDN Magazine article where the concepts are similar but uses a slightly different approach and still lack in any complexity. Are there any decent MVVM examples that at least show basic CRUD operations and dialog/content switching?
Everyone's suggestions were really useful and I will start compiling a list of good resources
Frameworks/Templates
WPF Model-View-ViewModel Toolkit
MVVM Light Toolkit
Prism
Caliburn
Cinch
Useful Articles
WPF Apps With The Model-View-ViewModel Design Pattern
Data Validation in .NET 3.5
Using a ViewModel to Provide Meaningful Validation Error Messages
Action based ViewModel and Model validation
Dialogs
Command Bindings in MVVM
More than just MVC for WPF
MVVM + Mediator Example
Application
Screencasts
Jason Dolinger on Model-View-ViewModel
Additional Libraries
WPF Disciples' improved Mediator Pattern implementation(I highly recommend this for applications that have more complex navigation)
MVVM Light Toolkit Messenger

Unfortunately there is no one great MVVM example app that does everything, and there are a lot of different approaches to doing things. First, you might want to get familiar with one of the app frameworks out there (Prism is a decent choice), because they provide you with convenient tools like dependency injection, commanding, event aggregation, etc to easily try out different patterns that suit you.
The prism release:
http://www.codeplex.com/CompositeWPF
It includes a pretty decent example app (the stock trader) along with a lot of smaller examples and how to's. At the very least it's a good demonstration of several common sub-patterns people use to make MVVM actually work. They have examples for both CRUD and dialogs, I believe.
Prism isn't necessarily for every project, but it's a good thing to get familiar with.
CRUD:
This part is pretty easy, WPF two way bindings make it really easy to edit most data. The real trick is to provide a model that makes it easy to set up the UI. At the very least you want to make sure that your ViewModel (or business object) implements INotifyPropertyChanged to support binding and you can bind properties straight to UI controls, but you may also want to implement IDataErrorInfo for validation. Typically, if you use some sort of an ORM solution setting up CRUD is a snap.
This article demonstrates simple crud operations:
http://dotnetslackers.com/articles/wpf/WPFDataBindingWithLINQ.aspx
It is built on LinqToSql, but that is irrelevant to the example - all that is important is that your business objects implement INotifyPropertyChanged (which classes generated by LinqToSql do). MVVM is not the point of that example, but I don't think it matters in this case.
This article demonstrates data validation
http://blogs.msdn.com/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx
Again, most ORM solutions generate classes that already implement IDataErrorInfo and typically provide a mechanism to make it easy to add custom validation rules.
Most of the time you can take an object(model) created by some ORM and wrap it in a ViewModel that holds it and commands for save/delete - and you're ready to bind UI straight to the model's properties.
The view would look like something like this (ViewModel has a property Item that holds the model, like a class created in the ORM):
<StackPanel>
<StackPanel DataContext=Item>
<TextBox Text="{Binding FirstName, Mode=TwoWay, ValidatesOnDataErrors=True}" />
<TextBox Text="{Binding LastName, Mode=TwoWay, ValidatesOnDataErrors=True}" />
</StackPanel>
<Button Command="{Binding SaveCommand}" />
<Button Command="{Binding CancelCommand}" />
</StackPanel>
Dialogs:
Dialogs and MVVM are a bit tricky. I prefer to use a flavor of the Mediator approach with dialogs, you can read a little more about it in this StackOverflow question:
WPF MVVM dialog example
My usual approach, which is not quite classic MVVM, can be summarized as follows:
A base class for a dialog ViewModel that exposes commands for commit and cancel actions, an event to lets the view know that a dialog is ready to be closed, and whatever else you will need in all of your dialogs.
A generic view for your dialog - this can be a window, or a custom "modal" overlay type control. At its heart it is a content presenter that we dump the viewmodel into, and it handles the wiring for closing the window - for example on data context change you can check if the new ViewModel is inherited from your base class, and if it is, subscribe to the relevant close event (the handler will assign the dialog result). If you provide alternative universal close functionality (the X button, for instance), you should make sure to run the relevant close command on the ViewModel as well.
Somewhere you need to provide data templates for your ViewModels, they can be very simple especially since you probably have a view for each dialog encapsulated in a separate control. The default data template for a ViewModel would then look something like this:
<DataTemplate DataType="{x:Type vmodels:AddressEditViewModel}">
<views:AddressEditView DataContext="{Binding}" />
</DataTemplate>
The dialog view needs to have access to these, because otherwise it won't know how to show the ViewModel, aside from the shared dialog UI its contents are basically this:
<ContentControl Content="{Binding}" />
The implicit data template will map the view to the model, but who launches it?
This is the not-so-mvvm part. One way to do it is to use a global event. What I think is a better thing to do is to use an event aggregator type setup, provided through dependency injection - this way the event is global to a container, not the whole app. Prism uses the unity framework for container semantics and dependency injection, and overall I like Unity quite a bit.
Usually, it makes sense for the root window to subscribe to this event - it can open the dialog and set its data context to the ViewModel that gets passed in with a raised event.
Setting this up in this way lets ViewModels ask the application to open a dialog and respond to user actions there without knowing anything about the UI so for the most part the MVVM-ness remains complete.
There are times, however, where the UI has to raise the dialogs, which can make things a bit trickier. Consider for example, if the dialog position depends on the location of the button that opens it. In this case you need to have some UI specific info when you request a dialog open. I generally create a separate class that holds a ViewModel and some relevant UI info. Unfortunately some coupling seems unavoidable there.
Pseudo code of a button handler that raises a dialog which needs element position data:
ButtonClickHandler(sender, args){
var vm = DataContext as ISomeDialogProvider; // check for null
var ui_vm = new ViewModelContainer();
// assign margin, width, or anything else that your custom dialog might require
...
ui_vm.ViewModel = vm.SomeDialogViewModel; // or .GetSomeDialogViewModel()
// raise the dialog show event
}
The dialog view will bind to position data, and pass the contained ViewModel to the inner ContentControl. The ViewModel itself still doesn't know anything about the UI.
In general I don't make use of the DialogResult return property of the ShowDialog() method or expect the thread to block until the dialog is closed. A non-standard modal dialog doesn't always work like that, and in a composite environment you often don't really want an event handler to block like that anyhow. I prefer to let the ViewModels deal with this - the creator of a ViewModel can subscribe to its relevant events, set commit/cancel methods, etc, so there is no need to rely on this UI mechanism.
So instead of this flow:
// in code behind
var result = somedialog.ShowDialog();
if (result == ...
I use:
// in view model
var vm = new SomeDialogViewModel(); // child view model
vm.CommitAction = delegate { this.DoSomething(vm); } // what happens on commit
vm.CancelAction = delegate { this.DoNothing(vm); } // what happens on cancel/close (optional)
// raise dialog request event on the container
I prefer it this way because most of my dialogs are non-blocking pseudo-modal controls and doing it this way seems more straightforward than working around it. Easy to unit test as well.

Jason Dolinger made a good screencast of MVVM. Like Egor mentioned there is no one good example. They are all over. Most are good MVVM examples, but not when you get into complex issues. Everyone has their own way. Laurent Bugnion has a good way to communicate between viewmodels as well. http://blog.galasoft.ch/archive/2009/09/27/mvvm-light-toolkit-messenger-v2-beta.aspx Cinch is also a good example. Paul Stovel has a good post that explains a lot too with his Magellan framework.

Have you looked at Caliburn? The ContactManager sample has a lot of good stuff in it. The generic WPF samples also provide a good overview of commands. The documentation is fairly good and the forums are active. Recommended!

Found this one useful. Has code too.
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

I have written a simple MVVM example from scratch on code project here is the link MVVM WPF step by step.
It starts from a simple 3 layer architecture and graduates you to use some framework like PRISM.

The sample project in the Cinch framework shows basic CRUD and navigation tools. It's a fairly good example of using MVVM, and includes a multi-part article explaining its usage and motivations.

I also shared in your frustration. I'm writing an application and I had these 3 requirements:
Extensible
WPF with MVVM
GPL compatible examples
All I found were bits and pieces, so I just started writing it the best I could. After I got into it a bit, I realized there might be other people (like yourself) who could use a reference application, so I refactored the generic stuff out into a WPF/MVVM application framework and released it under the LGPL. I named it SoapBox Core. If you go to the downloads page, you'll see it comes with a small demo application, and the source code for that demo application is also available for download. Hope you find that helpful. Also, email me at scott {at} soapboxautomation.com if you want more info.
EDIT: Also posted a CodeProject article explaining how it works.

Here I am adding link of a WPF(Inventory Management App) application which using MVVM architecture designed by me .
Its UI is awesome.
https://github.com/shivam01990/InventoryManagement

Even I shared the frustration until I took the matter into my hands. I started IncEditor.
IncEditor (http://inceditor.codeplex.com) is an editor that tries to introduce developers to WPF, MVVM & MEF. I started it and managed to get some functionality like 'theme' support. I am no expert in WPF or MVVM or MEF so I can't put a lot of functionality in it. I make a sincere request to you guys to make it better so that nutters like me can understand it better.

Related

Ways to attached an ICommand to a control in XAML

I'm very new to XAML. To utilize MVC architecture and the Command Pattern while taking advantage of XAML, I have started binding static ICommands to Buttons. I'm working on a fairly large project with over a hundred buttons. My questions are: are there different approaches for binding commands to buttons to avoid static objects. With regards to C#, WPF, and XAML, are statics commonly used? I'm sure someone has already worked on a project using MVC, Command Pattern, and XAML, what was your approach?
I should have probably edited this sooner, but while working on the project, I've realized how much I didn't know about c#, WPF, and XAML when I asked this question. Apparently, in WPF, instance properties make it convenient binding methods and data members to controls.
As far as MVC / MVVM are concerned, I guess I was hesitant to expose my model to VM before I even know what it is.
I think you mean the MVVM pattern as it applies to WPF. That is Model View ViewModel
Model = used to construct the form model for the data being manipulated
View = Presentation (usually a main form and many user control forms)
ViewModel = code container for presenter (classes that contain the code)
Generally your binding take the place of ICommand methods that implement a RelayCommand from a base. There is a lot to learn before implementing the MVVM model, I would suggest reading Josh Smith's article and downloading his example to get started on learning it:
There are special rules and principles to learn and this example will go through a lot of it.
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
I would also think it would be wise to learn how WPF performs bindings a little bit. There are many special setups you can do with bindings to help with performing operations at different events and other places. I do not even know all the bindings by heart but I know the more you learn them the more time you save in the end in your XAML coding as you can reuse, event trigger, inherit and do many things with bindings to make your applications more powerful than static creation.
http://msdn.microsoft.com/en-us/library/ms752347.aspx

View and ViewModel getting too large

While adding extra functionality to the main view I have in my application, I've realized that the amount of code will soon become a problem (currently around 600 lines of code in my viewmodel and I still have plenty to add).
I've been looking around for articles on how to split/design your view into smaller components, but I haven't found a satisfying solution. One person suggested using child viewmodels but that presented with other problems (dependency between the viewmodels).
I've thought of using user controls, but there is nothing on the View that I use on other Views so it kind of defeats the purpose of user controls.
What is a correct approach in this situation?
Thanks,
Adrian
If you want to split a view into component parts, then you need to do view composition. If you are building an MVVM app, then you should really be using an MVVM framework. Something like Caliburn.Micro makes view composition incredibly easy.
There doesn't necessarily have to be dependencies between the view models, they should only know about what they need in order to produce their view. This could be a subset of the business object that the parent view model contains. As the parent view model will have references to all of the child view models, it can pass the relevant parts of the business object to them at the point of their construction.
I would agree with using Caliburn Micro.
However, to play devil's advocate you could split out your ViewModel File into separate files (same class name) and use the partial keyword before the class keyword. Its generally tidier and one step-away (non-breaking precursor) from breaking-up into separate classes.
I also agree Caliburn.Micro is a good solution for splitting your application in smaller components.
In Caliburn.Micro the communication between viewmodels is based on the Event aggregator pattern.
This makes a loose coupling between viewmodels
Splitting up is not ideal.
It looks as if the Caliburn toolkit focuses on events, whereas my application largely relies on ICommand implementations.
To me, the first encounter with Caliburn.Micro has been unsatisfactory.
The setup appeared to be tailored to VS2010 - which sounded promissing to me - because I do have VS2010 pro. But I got lost in the setup's of Silverlight.
Compared to toolkits like Prism it lacks the ease of an start.
It just takes to much time to switch now.
I use my own MVVM paradigm, it is less abstract than the Caliburn, it integrates multilanguage support everywhere, and it just faces one acceptable problem of some sources getting too big because of the nature of the Binding/DataContext paradigm.
For this problem I accept that "partial class" is a solution - even though I know there is a more elegant solution available.
In the heat of my work, I cannot change to another toolkit.
So I gently wait for Microsoft to allow for more flexibility around that Binding/DataContext paradigm.
It may be the case that Caliburn shows more intelligence allocating a viewmodel to some item. Does it ? (I think it does.)
What might be another option is to define a custom (xaml useable) object that triggers a custom allocator which control is to be allocated to which viewmodel. How about that ?

Getting data from a view in MVVM?

I have a silverlight bing map application. I am using the MVVM pattern with PRISM.
The bing map has a "BoundingRectangle" property that is not available in XAML, but it is available via code behind. Of course this does me no good since I need the data in my viewmodel which doesn't have access to the View's code behind (nor do I want to add it, since I'd really like to try to not use the view's code behind if possible).
Normally, you would do a two way bind to a viewmodel property. The Bing map will surface BoundingRectangle for layers, but not for the base map (that I can find).
I'm not looking for a hack here, just wondering what the best practices or convention for getting data out of a view to a viewmodel that isn't "bindable".
Thanks!
Databinding in Silverlight is just a framework feature that automatically synchronizes data between your view and your view model (if you are following the MVVM pattern). However, there is nothing wrong with doing this yourself!
The two main advantages of the MVVM pattern (other than the usual separation of concerns that most UI patterns provide) are:
It aids unit testing, the View Model can be exercised from your unit test code without a view present.
It helps the developer / designer workflow, reducing the files shared between the designer and developer.
In my experience, having a small amount of code-behind that 'assists' the binding framework does no hard at all!
You can use techniques such as attached behaviours to wrap this code up, but often this just results in a cosmetic improvement.
CraigF,
you can use Mediator pattern, if you use Galasoft Light toolkit then use messenger to send message from view to your viewmodel. Viewmodel register to that message and if recive one set your property in viewmodel and do some logic..

What MVVM framework is Good For?

i know some Mvvm Frameworks that introduced in this thread
please describe or give me link for that what are them useful for?
not information about MVVM about MVVM Framework.
thanks :)
i want to know :
What Is MVVM Framework?
I think your question is not really precise. As far as I understand, you ask for the features of each framework?!
You can find detailed information here and here. However, at least one of these links has already been given in the thread you mentioned...
EDIT:
Basically, an MVVM framework is a collection of classes which are commonly used in applications utilising the MVVM (Model-View-ViewModel) pattern. This may include messaging systems to communicate between independent parts of a software, dependency injection techniques, base classes for ViewModels, project/class templates, validation mechanisms, commonly used commands, techniques for displaying dialog boxes, and so on...
To completely understand such a framework, you will have to understand the MVVM pattern first. Because only then (or even only after you did your first MVVM project) you will have an understanding of the problems and/or challenges of this pattern.
To use Mvvm framework just simply follow below steps:
You have a model and a view-model with the same name.
View-models are not supposed to be wrappers around models. The job of a view-model is to broker requests for external services such as the loading and saving of data. The data itself, as well as validation and most of the business logic, should be in the models.
I can’t emphasize this enough. Whenever you create a view-model that wraps a model by delegation you introduce a huge hole in your API. Specially, anything with a direct reference to the model can change a property in such a way that the view-model and thus the UI are never notified. Likewise, any changes to calculated fields in the model won’t be propagated back to the view-model.
You have a view and a view-model with the same name.
Ideally view-models are agnostic to the screens they are used by. This is especially true in a WPF application where multiple windows may be sharing the same instance of a view-model.
For smaller applications such you may only need a single view-model for the whole application. For larger applications you may need one for the main functionality and one for each secondary aspect such as configuration management.
You have no code behind.
In absolute terms code behind is neither a good nor a bad thing. It is merely a place to put logic that is specific to a single view or control. So when I see a view with no code-behind at all I immediately check for the following mistakes:
Does the view-model touch specific controls by name?
Is the view-model being given access to controls via a command parameter?
Is EventToCommand or another leaky behavior being used in place of simple event handler?
EventToCommand from MVVM Light is especially bad because it will prevent controls from being garbage collected after they are removed from the screen.
View-models are listening to property changed notifications
If a model has a longer life-span then the view-model that listens to its events then you probably have a memory leak. Unlike views which have an unloaded event, view-models don’t have a good story for life-cycle management. So if they attach an event to a model that may out-last them then the view-model will be leaked.

Confusion regarding MVVM pattern and dynamic loading of XAML in GUI

Well this question relates to MVVM pattern and i could good and fast answers on this forum so I thought to ask and clear the confusions i had about the pattern.
I am quite new to MVVM approach. I appreciate the pattern and understand the principals behind it. Maybe I have not worked that much with the pattern that’s why there are a few confusions.
If there is a scenario in which I want to load few parts of my WPF page dynamically with XAML and still want to be compliant with MVVM approach.
The confusion is:
Where the logic of loading a view dynamically with XAML reside.
Whether I should have a single ViewModel for my WPF page or each seperate part have its own viewmodel with interactions with other viewmodel classes.
What if I had to build control tree displayed on the GUI using C# code in the codebehind itself.
For the controls created using code should I do the commandbindings in the codebehind of the view itself.
Where the logic for loading goes is something not really addressed by the pattern itself. There's an interesting blog post about this by Ward Bell. There's any number of ways to skin this cat, and they're all compatible with MVVM. Not really the answer you're looking for, I know, but it's honest :). Check out Ward's blog post... you'll get a much more in depth discussion of this topic.
As for whether or not to have a single VM for the page, or one for each control, that just depends. Generally, I have one for the page. If there's some portion that reusable elsewhere, I break it out into a user control with it's own VM, which means we have a VM within a VM. I don't agree with rockeye on this one. There isn't a one-to-one relationship between V-VM-M. You're Models are designed according to business needs, with NO regard to presentation at all. You're ViewModels are designed according to your presentation needs, and may encapsulate more than one Model. In fact, it's very common for them to encapsulate many models.
Like rockeye, I don't understand your last question.
I am also quite new to mvvm, but i will try to answer :
Where the logic of loading a view dynamically with XAML reside
If you mean "how can i show the view associated with my business object?", IMHO, you don't have to care about this. Usually, your VMs have corresponding views. With dataTemplate, you use only VM in the code but Views are displayed automatically.
2 Whether i should have a single ViewModel for my WPF page or each seperate part have its own viewmodel with interactions with other viewmodel classes
It seems you have a top-bottom approach. I see the mvvm more as bottom-up : models (business objects) -> ViewModels -> Views. Every model should have its own ViewModel and view. So you can't have a whole WPF page in a viewModel unless you model represents a page.
3 What if i had to build control tree displayed on the GUI using C# code in the codebehind itself. For the controls created using code should i do the commandbindings in the codebehind of the view itself.
Don't understand. I think you may take a look at dataTemplate, it might be helpfull.

Resources