WPF MVVM calling ViewModel methods from code behind - c#

First off I am very new to WPF MVVM and a bit confused. People say that generally in MVVM the best practice is not to have any code behind. I have found that some methods are way easier to achieve in code behind than in viewmodel (e.g MouseMove) and that led me thinking between the differences of these 2 following examples:
1) Using RelayCommand:
View
<Button Command="{Binding AlertCommand}"></Button>
ViewModel
public RelayCommand AlertCommand { get; set; }
public void Alert()
{
MessageBox.Show("message");
}
2) calling ViewModel methods from code behind:
View
<Button PreviewMouseLeftButtonUp="OnMouseLeftButtonUp"></Button>
View code behind
private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var ctx = (MainViewModel) this.DataContext;
ctx.Alert();
}
Is using code behind here wrong? What are my benefits of not using code behind?

The MVVM pattern is a best practice when building UWP, WPF, and Xamarin.Forms apps. The main advantage is that you are able to decouple the logic from the presentation and potentially could present a single view model by multiple different views and could switch views without having to modify the view model significantly. This is a great advantage when building cross-platform apps with native UI, which MvvmCross framework uses to a great extent for example.
Having an empty code-behind is however definitely just an ideal, which is usually not easy and not always necessary to achieve. Sometimes you need to use code-behind for purely view-related manipulation like changing layout for different window sizes, controlling animations, etc. For such actions, code-behind is a much better fit than trying to force this somehow into the VM.
Comparing your two approaches, using the RelayCommand-based one over the direct method call is preferable, because it has less direct tie to the method itself. If you wanted, you could switch the RelayCommand instance in the VM for a different implementation (calling different method) at runtime, and thanks to binding the button could now perform a different action. This can be used in editor-like apps where some tools may have different functionality based on current context the app is in.
Also, for controls which do not offer a Command you can use EventTrigger hand in hand with InvokeCommandAction (both defined withing Expression Blend SDK) which will allow you to "convert" an event to a command call, even with your defined transformation of EventArgs.

Both are valid methods. The first is preferable if possible. I generally use the second method on events where no command binding is available. The notion of "absolutely no code-behind in MVVM" is debatable. Any code that belongs directly to the view (and is not business logic) and is not reusable in a VM can be put in the code-behind, such as wiring up events in the second example.

Related

Clean and elegant view models in WPF

Once I found out MVVM I really liked it. The whole concept of binding, separating view from logic, testability, etc was very encouraging. It was a nice alternative for the messy, never-ending code behind. Than I learned there are commands that can be bound, which I also liked at first.
Having written a couple of controls using MVVM though I found out that my view models start to look more or less like code behind. Full of commands that did almost exactly what was previously done in code behind by event handlers.
Let me give you some examples.
There is a control with a button "Details" which opens another window.
[approach 1]
The first (and worst) thing you can do is call something like this in your command:
new DetailsWindow().ShowDialog();
That makes the view model strongly reference the presentation layer - ugly.
[approach 2]
Lets fix this problem using a weak reference and create something like IDialogService. We can inject a simple implementation that creates and opens the window. Now we got rid of the strong reference to the presentation layer and the command can look like this:
_dialogService.ShowDetailsWindow();
I still don't like this approach. To me it feels like the view model is not something that should decide whether to show a window or not. It should serve and handle data.
[approach 3]
The elegant way to totally separate the view model from the presentation layer would be to inject the command itself. Than the view model would not be aware of presentation layer. It would only execute the injected action - no matter what it is.
Question 1:
Which approach would be best? I guess the number 3 is the winner.
Question 2:
Should this even be a part of the view model? I think it shouldn't as it seems to be the concern of the presentation layer. Maybe it's best to put it in a simple event handler in code behind?
The second example is more complex. In the same control we have a "Delete" button. It should open a dialog asking user for confirmation and if he says 'yes' it should delete something. In this case it makes more sense to put it in the view model as it really affects the data.
Question 3
This case is the most tricky for me. I can't use my favorite approach number 3, because I have to display a dialog which is a presentation layer's job, but also I have to perform some logic depending the dialog's result - which on the other hand is view model's job. What is the best approach here?
Please bare in mind that I really don't want to use approaches 1 and 2. I want the view model to be clean and unaware of anything related to the presentation layer - not even by weak references.
One thing that comes to my mind it to split the view model layer into two layers. Something like:
view --> presentation view model --> logic view model
presentation view model
used as a control's context
contains logic view model as a public property for direct bindings
uses approach number 2 - now it's acceptable as the whole class is meant to perform presentation related actions
logic view model
it is 'presentation free'
references specialized logic services
some commands could be bound directly to the view
some commands could be executed by the presentation view model which owns it
Maybe this is the right way to go?
[EDIT]
In response to the suggestions in comments about using a framework:
Using a framework will surely make it easier to handle windows, but it's not the solution to the problem. I don't want the 'logic view model' to handle windows at all, not even with a help of a framework. Referring to the approach I suggested at the end I would still put it in the 'presentation view model'
Your ViewModel should just notify all the subscribers that the command was executed by firing a simple event. The View should subscribe to that event and handle the event by displaying a new Window...
ViewModel:
public event EventHandler<NotificationEventArgs<string>> DisplayDetailsNotice;
private DelegateCommand displayDetailsCommand;
public DelegateCommand DisplayDetailsCommand
{
get { return displayDetailsCommand ?? (displayDetailsCommand = new DelegateCommand(DisplayDetails)); }
}
public void DisplayDetailsWindow()
{
//
Notify(DisplayDetailsNotice, new NotificationEventArgs<string("DisplayDetails"));
}
View (note that the VM is already the DataContext of the View):
private readonly MyViewModel mvm;
//Get reference to VM and subscribe to VM event(s) in Constructor
mvm = DataContext as MyViewModel;
if (mvm == null) return;
mvm.DisplayDetailsNotice += DisplayDetails;
private void DisplayDetails(object sender, NotificationEventArgs<string> e)
{
DetailsWindow = new DetailsWindow { Owner = this };
DetailsWindow.ShowDialog();
}
This way, when the command is executed the VM raises the event and the View which is subscribed to VM events handles the event by displaying the details windows using the ShowDialog() method. Since all the VM does is publish an event it remains agnostic of and decoupled from the View leaving the MVVM pattern intact. Since VM is already the DataContext of the View and the View binds to properties of the VM as it is obtaining a reference to the VM is also not breaking the MVVM pattern...
Note that this syntax is valid with Simple MVVM Toolkit MVVM framework. As suggested in comments you should start using an MVVM framework (my recommendations are Simple MVVM Toolkit or MVVM Light, Caliburn is too complex for no reason and no gain IMO) in order to avoid having to deal with the plumbing yourself...

What is the recommended way to open a new window using MVVM in WPF

Hello everyone and thanks in advance for your time.
I'm currently learning MVVM using WPF for a small Biz App that I'm writing. I have read a lot of articles about the MVVM pattern and found that one of the key areas is to decouple the ViewModel from the View as much as possible.
I want to open a new Window in my app but I'm not sure if I should open it from the ViewModel using an ICommand or directly from the view using a standard event. Someone I work with suggested that that I should use commands, but then I thought that this would mean having a reference to a View in my ViewModel, which according to what I understand is precisely what the MVVM pattern focuses on avoiding.
My understanding is that if a window will open for navigation purposes only and the process of opening that new windows has no effect on the Model, then I should keep all of this on the view using standard events.
I know in sw development everything "depends", but guess my question is there a "right"/standard way of doing this?
Best regards,
Daniel
Yes, VMs should communicate with Views utilizing the Events that Views can subscribe to...
In VM:
public event EventHandler<NotificationEventArgs<string>> DisplayOptionsNotice;
In View:
private readonly MainViewModel mvm;
...
mvm = DataContext as MainViewModel;
mvm.DisplayOptionsNotice += DisplayOptionsWindow;
...
private void DisplayOptionsWindow(object sender, NotificationEventArgs<string> e)
{
...
optionsWindow = new OptionsWindow { Owner = this };
optionsWindow.ShowDialog();
...
}
but then I thought that this would mean having a reference to a View in my ViewModel, which according to what I understand is precisely what the MVVM pattern focuses on avoiding.
In general, the way this is handled is via some form of inversion of control. Most MVVM frameworks will provide a service of some form to open a window, and use a Service Locator or Dependency Injection to provide the service to the ViewModel.
This allows your ViewModel to stay decoupled from the specific view rendering framework - you'd pass the service the new VM and say "Show this VM in a window", and that code would be platform specific.
As Reed said Service locator or DI will do the work and wont breake the MVVM pattern.
from my experience you will have to do three things:
First check about the Service Locator or Di see what more friendly for you and implement it.
Second start making the interface of IWindow\IWindowDialog that your view (windows\ Messagebox - if you like) will implement for example.
the last thing is to implement the windows\ messages.
it will take time to do it from scratch (I did it) but if you will focus one thing at a time.
you cut the time in half.
Good luck

Why is ICommand better than code behind calling the VM?

I have a co-worker that asked me why he has to use the ICommand pattern.
He wants to add a button and then make an event for it in the code behind. Then from the event he wants to call a method on the ViewModel.
I gave him the obvious answer: This adds coupling between the View and the ViewModel. But he argued that the View and the ViewModel are already coupled. (We set our view's DataContext to the ViewModel in the View's code behind: DataContext = new MyViewModel();
Yes, I told him that his way adds "more coupling", but it sounded a bit lame even to me.
So, I know that ICommand is the clean way, and I do it that way. But what else does ICommand buy you besides not using an already existing coupling?
It's not about decoupling, but how deep you can penetrate inside your ModelView hierarchy: not event pumping, but event routing, built-in in the framework.
It's about UI managent: Command has state (CanExecute), if assign the command to the control, if command's state becomes false, control becomes disabled. It gives you powerful UI state management way, avoiding a lot of spaghetti coding, for complicated UI especially.
I have a co-worker that asked me why he has to use the ICommand
pattern.
It seems implied this is a standard at your company (whether explicitly stated or unspoken). That should be answer enough to his question.
If all company code is supposed to use that pattern, it can cause co-developer confusion and frustration when someone else has to debug his code.
Also, in my opinion, using ICommand is faster to develop / mock up because you don't NEED to have the ICommand property on the context to run your program. It lets your UI designers (if you are lucky enough to have them) completely finish their tasks even if you are behind in your coding.
ICommand can also give you a place for handling wether or not a specific button can be used right then. this would be handled through the canexecute method.
You can bind the CanExecute method of the command to the properties of a control, also a Command encapsulates an action in a nice way. In my opinion / experience this approach makes a lot of sense because you have both the condition and the execute action in a single abstraction, which makes it easier to understand and test.
If in the future you find that this action is repeated you can abstract it easily in your own custom ICommand and use it in several places.
One thing that I don't see in the previous answers is that using the ICommand promotes code reuse by allowing the same action to be used by different GUI components. For example, if I had a command that should result in the opening of a window and that command could be invoked in three or for different screens in the application, an ICommand implementation lets me define that logic in a single place. With the code-behind event handlers, I have to copy and paste redundant code, in violation of DRY (or else, I'd have to roll my own implementation by abstracting out to a class, at which point, I might as well use ICommand).

MVVM Foundation: How to close Application Window from ViewModel

I am using MVVM Foundation but I think its quite straight-forward and not really framework specific. My setup is as follows:
StartViewModel - has a ExitCommand that returns a RelayCommand/ICommand
public ICommand ExitCommand {
get { return _exitCommand ?? (_exitCommand = new RelayCommand(() => MessageBox.Show("Hello World"))); }
}
public RelayCommand _exitCommand;
StartView (User Control) has a button binded to the ExitCommand
<Button Content="Exit" Command="{Binding ExitCommand}" />
First, read as much as you can stomach on MVVM, e.g. WPF Apps With The Model-View-ViewModel Design Pattern on MSDN. Once you understand the basic principles driving it the answer will seem more reasonable.
Basically you want to keep your View (UI) and ViewModel (essentially abstract UI, but also abstract Model) layers separate and decoupled. Showing a message box or closing a window should be considered a UI specific detail and therefore implemented in the View, or in the case of a message box, more generally available via a 'Service'.
With respect to the ViewModel, this is achieved using Inversion of Control (IoC). Take the message box example above. Rather than showing the message box itself, it takes a dependency on an IMessageBoxService which has a Show method and the ViewModel calls that instead - delegating responsibility. This could be taken further by leveraging Dependency Injection (DI) containers.
Another approach used for closing a View window might be for the ViewModel to expose an event, called for example RequestClose (as in the MSDN article), that the View subscribes to. Then the ViewModel would raise the event when it wants the corresponding View / window to close; it assumes something else is listening and will take responsibility and actually do it.
you can implement an CloseEvent in your StartViewModel. in your StartView you have to register this CloseEvent. when you Raise your closeevent from your VM then, your View recognize that it has to close your app/window.

Having trouble deciding how to wire up a UserControl with MVVM

I've been doing the best I can to try to stay true to the separation recommended by the MVVM pattern. One thing I haven't figure out how to do correctly has to do with initializing my UserControls.
My most recent example of this has to do with a library that I wrote to talk to some low-level hardware. That assembly happens to have a UserControl that I can simply drop into any GUI that uses this hardware. All that is necessary for it to work is to set a reference to the object that has access to the low level methods.
However, that's where my problem lies -- currently, the UserControl is added to the GUI via XAML, where I define the namespace and then add the UserControl to my window. Of course, I have no control over its creation at this point, so the default constructor gets called. The only way to set the necessary reference for hardware control involves calling a method in the UC to do so. The ViewModel could feasibly call a method in the Model, e.g. GetController(), and then call the method in the UserControl to set the reference accordingly. The GUI can pass a reference to the UserControl to the ViewModel when said GUI creates the ViewModel, but this violates MVVM because the ViewModel shouldn't know anything about this control.
Another way I could deal with this is to not create the UserControl in XAML, but instead do it all from code-behind. After the ViewModel gets initialized and retrieves an initialized UserControl (i.e. one that has the low-level object reference set), it can set the Content of my Window to the UserControl. However, this also violates MVVM -- is there a way to databind the Content of a Window, TabControl, or any other element to a UserControl?
I'd like to hear if anyone has had to deal with this before, and if they approached it the first or second way I have outlined here, or if they took a completely different approach. If what I have asked here is unclear, please let me know and I'll do my best to update it with more information, diagrams, etc.
UPDATE
Thanks for the responses, guys, but I must not have explained the problem very well. I already use RelayCommands within the UserControl's ViewModel to handle all of the calls to the hardware layer (Model) when the user clicks in the control in the UserControl itself. My problem is related to initially passing a reference to the UserControl so it can talk to the hardware layer.
If I create the UserControl directly in XAML, then I can't pass it this reference via a constructor because I can only use the default constructor. The solution I have in place right now does not look MVVM-compliant -- I had to name the UserControl in XAML, and then in the code-behind (i.e. for the View), I have to call a method that I had added to be able to set this reference. For example, I have a GUI UserControl that contains the diagnostics UserControl for my hardware:
partial class GUI : UserControl
{
private MainViewModel ViewModel { get; set; }
public GUI( Model.MainModel model)
{
InitializeComponent();
ViewModel = new MainViewModel( model, this.Dispatcher);
ViewModel.Initialize();
this.DataContext = ViewModel;
diagnostics_toolbar.SetViewModel( ViewModel);
user_control_in_xaml.SetHardwareConnection( model.Connection);
}
}
where the outer class is the main GUI UserControl, and user_control_in_xaml is the UserControl I had to name in the GUI's XAML.
Looking at this again, I realize that it's probably okay to go with the naming approach because it's all used within the View itself. I'm not sure about passing the model information to user_control_in_xaml, because this means that a designer would have to know to call this method if he is to redo the GUI -- I thought the idea was to hide model details from the View layer, but I'm not sure how else to do this.
You will also notice that the main GUI is passed the Model in the constructor, which I assume is equally bad. Perhaps I need to revisit the design to see if it's possible to have the ViewModel create the Model, which is what I usually do, but in this case I can't remember why I had to create it outside of the GUI.
Am new to MVVM myself but here's a possible solution:
Create a property in your VM that is of the object type (that controls the hardware) and bind it to an attached property on your UserControl. Then you could set the property in your VM using dependency injection, so it would be set when the VM is created. The way I see it, the class that talks to the hardware (hardware controller) is a service. The service can be injected to your view model and bound to your UserControl. Am not sure if this is the best way to do it and if it is strict enough to all the MVVM principles but it seems like a possible solution.
if your question is: How do i show my viewmodel in the view? then my solution is always using viewmodelfirst approach and datatemplates.
so all you have to do is wire up your viewmodel via binding to a contentcontrol.content in xaml. wpf + datatemplates will do the work and instantiate your usercontrol for your viewmodel.
You are right, the ViewModel shouldn't know about anything in the View - or even that there is such a thing as a View, hence why MVVM rocks for unit testing too as the VM couldn't care less if it is exposing itself to a View or a test framework.
As far as I can see you might have to refactor things a little if you can. To stick to the MVVM pattern you could expose an ICommand, the ICommand calls an internal VM method that goes and gets the data (or whatever) from the Model, this method then updates an ObservableCollection property of the data objects for the View to bind to. So for example, in your VM you could have
private ICommand _getDataCommand;
public ICommand GetDataCommand
{
get
{
if (this._getDataCommand == null)
{
this._getDataCommand = new RelayCommand(param => this.GetMyData(), param => true);
}
return this._getDataCommand;
}
}
private void GetMyData{
//go and get data from Model and add to the MyControls collection
}
private ObservableCollection<MyUserControls> _uc;
public ObservableCollection<MyUserControls> MyControls
{
get
{
if (this._uc == null)
{
this._uc = new ObservableCollection<MyUserControls>();
}
return this._uc;
}
}
For the RelayCommand check out Josh Smiths MSDN article.
In the View you could either call the ICommand in the static constructor of your UC - I am guessing youwould need to add an event in your class for this - or call the ICommand from some sort of click event on your UC - maybe just have a 'load' button on the WPF window. And set the databinding of your UC to be the exposed observable collection of the VM.
If you can't change your UC at all then you could derive a new class from it and override certain behaviour.
Hope that helps a bit at least, like I say, have a look at Josh Smiths MVVM article as he covers the binding and ICommand stuff in there brilliantly.
If you set the DataContext of the Window or UserControl containing thisUserControl to the main view model, the user control can call SetHardwareConnection() on itself in its Loaded event (or DataContextChanged event handler).
If that's not possible because you're saying the UserControl is 'fixed', you should derive from it or wrap it up in another UserControl, which would serve as a MVVM 'adapter'.
(In order to bind the window: you could make the MainViewModel a singleton with a static Instance property and use DataContext="{x:Static MyClass.Instance}". A nice way to get things going quickly)
Note; this is based on my understanding that MVVM works because of Bindings.. I always bind the control to a ViewModel, not pass a ViewModel as a parameter.
Hope that helps!

Categories

Resources