MVVM - Pertaining to WPF command binding standards - wpf

I think I have a pretty good understanding of the MVVM design model, however I have a quarm with it in regards to WPF, Command bindings and how we are meant to use them.
To bind commands to the XAML directly we are meant to implement the ICommand interface within the ViewModel. Now, the ICommand interface is part of the PresentationCore.DLL, which, correct me if im wrong is part of WPF not the base .NET framework.
Isnt the whole point of the ViewModel and Model that it should be totally UI independant? For example, if I implement ICommand in my ViewModel and use it as a data context in order to bind commands from the XAML, isnt my ViewModel then dependant on the WPF frame work (in particular the PresentationCore.Dll).
What I mean is, if I was to go and try to use my Models and ViewModels in lets say a Windows Forms environment, I would have to reference the PresentationCore.DLL even though I shouldnt need it because im using Windows Forms not the WPF framework.
This seems a bit odd to me, am I missing something here? Is there another way I should be doing it to keep my Model and ViewModel totally UI and UI Framework independant, but still be able to utilise the Command binding in XAML?
Thanks in advance!

I also had this kind of problem but not in wpf but in POCO classes. What i did was I created two partial classes in two different assemblies. Like you create one partial class which is not presentationcore.dll dependent in your VM project and create its partial class in another assembly(say WPFVM) which implements ICommand stuff. Now for Winforms stuff add only VM project reference to View project and for WPF stuff add references of both VM and WPFVM to the View project. I hope this will help.

The point of MVVM is to have the view just be a view, and nothing more. Putting ICommands into the view model helps this as it pulls the code away from the view. Where you will run into problems is if you have to access something on the view that is not a dependency property, which means you can not bind to it.

In my opinion MVVM is very popular with the WPF, Silverlight because it naturally fits into it. The data binding concept in the XAML allows the Views & ViewModels to be bridged using a single property which is the DataContext. As no longer your logic is tied to controls, you get better testability, design-code separation and maintainability. You may be able to implement the MVVM pattern in other places also, but in WPF and Silverlight, it fits so easily due to its data and command binding support. I have read somewhere that, Don't take patterns religiously. They were made to make your life simpler rather than giving you more problems while following it. For Winforms i think there are better patterns, If you are focusing in reusing the business logic, move them out of your ViewModels to seperate classes something like serviceproviders or serviceagents and share them between your Winforms and WPF apps.

This has changed in .NET 4.5 compare
.NET Framework 4.5
.NET Framework 4

Related

Ambiguous between Microsoft Sample and WPF Rules

I thought we should have no reference from View to ViewModel in MVVM Pattern. but just saw an MVVM Sample from code.msdn.microsoft in which ViewModel implements new Window and shows it;
By using MVVM-Light toolkit you use Messenger to Call or Open new Window and Still keep Separate the View and ViewModel form each other. Is it right to reference the View in ViewModel? Or it is wrong;
Do you suggest to call Views Directly from ViewModel for large(or medium) projects?
http://code.msdn.microsoft.com/windowsdesktop/Easy-MVVM-Examples-fb8c409f
YAGNI.
Level of effort and complexity.
MVVM is just a pattern. A pattern you don't have to follow. Any little tool I write for my own use just uses a model, a viewmodel, and a view. The viewmodel exposes all properties I need for the view by INotifyPropertyChanged. The data is moved back and forth from viewmodel to model manually using ViewModel.FromModel(model) syntax. I don't bind to my models. I only use the model when saving/loading data; I don't hang onto it. My views are generated using dataTemplates and dataTemplateSelectors. If I have a property that should change the layout I expose that on the viewmodel and use a selector. Otherwise, I have a datatemplate for every viewmodel object. And it just works.
I call this a form of MVVM, even though it doesn't any toolkit or the exact MVVM pattern that Microsoft describes.
I would personally implement a service to drive commands from the viewmodel to generate new views and hookup the viewmodel. But that's because I have MVC experience, and I think generating views is easier to do using the MVC pattern, whereas desktop views work better using the MVVM pattern.
All my views are composed with contentControls. Setting the content is setting the viewmodel.
So I use a hybrid.
If your software isn't so complex to need the complete Microsoft endorsed MVVM pattern, why create the overhead code IMO. YAGNI.
IMO, having a strong reference from the ViewModel to the View has 2 problems:
It breaks the testability of your ViewModel code. This means you won't be able to Unit Test your code so easily, and if you do you'll have to account for Dispatcher issues and the like.
It makes your ViewModels dependent on WPF assemblies and types. This means you won't be able to literally copy and paste your ViewModels into other applications or platforms such as Xamarin.Android or the like
If none of these are important to you, I don't see any reason why you wouldn't. Not doing so creates additional overhead in your code, by having to implement WindowManagers and whatnot.

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

Common shared views. Views + ViewModels or UserControls?

I am developing a little utility view that will be embedded in several of our apps. It will sit in a common library.
Should I expose this as a ViewModel along with a default View implementation, or would it be better as a UserControl with a fixed GUI?
It is pretty self contained and I doubt it will need to be reskinned, but doing it as a UserControl seems a bit overkill with having to set up a load of dependency properties.
A simple ViewModel seems more attractive to me but wondered if this was the normal way of sharing stuff?
EDIT:
It would also be nice if I could embed this in WinForms apps too. Is this possible with View/ViewModel?
Well, in the end I went with View/ViewModel. This keeps the separation nicely and is easily pluggable into existing MVVM projects.
It also works fine in WinForms, given that a View is just a UserControl with its DataContext set to some arbitrary object (the ViewModel).
The only slight issue I had was the fact that Application.Current is not set in a forms environment, so I had to store the GUI dispatcher reference so I could marshal gui updates to the proper thread in my ViewModel.

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..

Where should the viewModel be created?

I have seen a few examples where the viewModel (in Silverlight apps) is in the UserControl.Resources XAML section of a View. I read that for using Blend, this is a good place to have it (as it gives the ability to see sample data in Blend).
However, is this the best place to have the viewModel? I read that the "view has to push services to the viewModel". What does this mean and where else could or should the ViewModel be created?
Thanks.
JD.
There are lots of ways that the View and the ViewModel can be connected. The simplest approach is using the Resources like you mention or even easy just setting the DataContext of the View in the Xaml to an instance of the ViewModel.
From there things get more complex and really it depends on the framework you use:
Silverlight.FX - Uses a View base class with a Model property.
MVVM Light - Uses a ViewModelLocator.
Prism - Controllers
Caliburn - Presenters
So the approach you take will depend on what style you like. There are many ways to do this and right now there are a lot of MVVM frameworks showing up.

Resources