Reuse controls inside a usercontrol - wpf

I have a UserControl UserControl1 and a button inside the UserControl1. And I have a UserControl1ViewModel that has an ICommand property for the button. Using this command I need to call a method outside(from other VMs or VM of the MainWindow) the VM. What is the best practice for this?

You might want to examine MVVM lite by Laurent Bugnion http://www.galasoft.ch/mvvm/getstarted/
This is a lightweight toolkit for helping enforce mvvm concepts. In it, every viewmodel is a static member in a ViewModelLocator class. So for instance, in your command you could do something like this.
ViewModelLocator.MainViewModel.MainContent = NewContent;
You can totally do this without mvvm lite, but using it really helps speed up the learning curve and enforce modularity.

You're most likely looking to implement the Mediator pattern to handle the communication between two viewmodels.
Another SO question along the same vein is:
mvvm-view-model-view-model-communications

I would consider using Controllers for the mediation between the ViewModels. The WPF Application Framework (WAF) shows how this works.

Related

Where do I handle the WPF commands?

I have a whole bunch of RoutedUICommand commands which I fire from different places, using the Command attribute in XAML.
They all are bound right now in my MainWindow.xaml and in my MainWindow.xaml.cs I have a handler for each of them. I have set it up this way, mostly because I resolve the MainWindow class with Unity and it receives all necessary dependencies (i.e. domain services and etc). If I bind the command to a UserControl, I wouldn't have those services available there and also it seems wrong that a UserControl which is given a DataContext, but would be allowed to manipulate its or another context.
My question: does this seem right? To me, something seems off about handling all of the commands in a single central place, especially the main window code behind.
I am new to WPF and can't tell if this is right or wrong. Any advice is appreciated.
You should handle them in your ViewModel. The common pattern in WPF applications is MVVM.
M - model (i.e. DB)
V - view (.xaml files)
VM - a class that is set to be the DataContext for you view. You should do all the logic, binding here.
I suggest having a look at some MVVM frameworks that can simplify the development.
Some of the popular ones are:
Caliburn.Micro
MVVM Light
WPF provides two implementations of the ICommand interface; the System.Windows.Input.RoutedCommand and System.Windows.Input.RoutedUICommand where the latter is a subclass of the former that simply adds a Text property that describes the command.
However, neither of these implementations are especially suited to be used in a view model as they search the visual tree from the focused element and up for an element that has a matching System.Windows.Input.CommandBinding object in its CommandBindings collection and then executes the Execute delegate for this particular CommandBinding.
Since the command logic should reside in the view model, you don’t want to setup a CommandBinding in the view in order to connect the command to a visual element. Instead you should create your own command by creating a class that implements the ICommand. All MVVM libraries out there such as Prism, MvvmLight and Caliburn Micro already have such an implementation. They are usually called DelegateCommand or RelayCommand. Please refer to the following links for more information about commands and how to use them in an MVVM WPF application.
MVVM - Commands, RelayCommands and EventToCommand: https://msdn.microsoft.com/en-us/magazine/dn237302.aspx
Handling events in an MVVM WPF application: https://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/

Does using a DataTemplate in the View create a coupling between View and ViewModel?

I just started looking into WPF and MVVM-Light a couple of days ago. At first I created a single windows desktop app and now I want to create a desktop app with several pages.
I read this tutorial and I think I understand the concept.
But I have one question. MVVM-Light uses the ViewModelLocator to avoid having a strong link between the view and the viewmodel. But does using a DataTemplate in the MainWindow.xaml (to associate view and viewModel) not go against this principle? Is this the right way to do it?
Lots of people use the DataTemplate method,that's fine. The other widely used method, setting DataContext to your ViewModel in code-behind, also creates a "link" between them. If there is no link, nothing would ever work at all.

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

MVVM - Pertaining to WPF command binding standards

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

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

Resources