Is accessing the ViewModel in code behind always violating the MVVM pattern? - c#

One thing I am really not sure about is how to properly pass mouse events to the ViewModel. There is the way of binding triggers using the interactivity extension like for instance in: WPF event binding from View to ViewModel?
But this does not forward the MouseEventArgs to my knowledge, and this solution does not appear very elegant to me.
So what would be the proper solution? One way is to register an event and to handle it in the code behind, e.g.:
private void ListBox_PreviewMouseDown(object sender, System.Windows.Input.MouseEventArgs e)
{
var listbox = sender as ListBox;
if (listbox == null)
return;
var vm = listbox.DataContext as MainViewModel;
if (vm == null)
return;
// access the source of the listbox in viewmodel
double x = e.GetPosition(listbox).X;
double y = e.GetPosition(listbox).Y;
vm.Nodes.Add(new Node(x, y));
}
Here I assume that the listbox's ItemsSource is bound to the vm.Nodes property. So again the question: is it the proper way of doing it? Or is there a better one?

Good timing, I wrote some code to do exactly this about two hours ago. You can indeed pass arguments, and personally I thnk it is elegant because it allows you to fully test your user interface. MVVM Lite allows you to bind events to commands with EventToCommand, so start by adding the relevant namespaces to your control/window:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:cmd ="http://www.galasoft.ch/mvvmlight"
Now add event triggers to the child control whose events you want to intercept:
<ItemsControl ... etc ... >
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDown">
<cmd:EventToCommand Command="{Binding Mode=OneWay, Path=MouseDownCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
<i:EventTrigger EventName="MouseUp">
<cmd:EventToCommand Command="{Binding Mode=OneWay, Path=MouseUpCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
<i:EventTrigger EventName="MouseMove">
<cmd:EventToCommand Command="{Binding Mode=OneWay, Path=MouseMoveCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ItemsControl>
In my specific case I'm rendering a collection of items onto a canvas, hence my use of ItemsControl, but it'll work on anything including the parent window. It will also work for key strokes (e.g. KeyDown) but if your child control isn't focus-able then you'll have to add the trigger to the parent instead. In any case all that remains is to add the relevant handlers to your view model:
public class MyViewModel : ViewModelBase
{
public ICommand MouseDownCommand { get; set; }
public ICommand MouseUpCommand { get; set; }
public ICommand MouseMoveCommand { get; set; }
public ICommand KeyDownCommand { get; set; }
// I'm using a dependency injection framework which is why I'm
// doing this here, otherwise you could do it in the constructor
[InjectionMethod]
public void Init()
{
this.MouseDownCommand = new RelayCommand<MouseButtonEventArgs>(args => OnMouseDown(args));
this.MouseUpCommand = new RelayCommand<MouseButtonEventArgs>(args => OnMouseUp(args));
this.MouseMoveCommand = new RelayCommand<MouseEventArgs>(args => OnMouseMove(args));
this.KeyDownCommand = new RelayCommand<KeyEventArgs>(args => OnKeyDown(args));
}
private void OnMouseDown(MouseButtonEventArgs args)
{
// handle mouse press here
}
// OnMouseUp, OnMouseMove and OnKeyDown handlers go here
}
One last thing I will mention that is only a little bit off-topic is that often you'll need to communicate back to the code-behind e.g. when the user presses the left mouse button you might need to capture the mouse, but this can easily be accomplished with attached behaviors. The mouse capture behavior is simple enough, you just add a "MouseCaptured" boolean property to your view model, bind your attached behavior to it and have it's changed handler respond accordingly. For anything more complicated you might want to create an event inside your view model which your attached behaviour can then subscribe to. Either way, your UI is now fully unit-testable and your code-behind has been moved into generic behaviors for re-use in other classes.

I think your approach is good. Those events, that work with View, can be in your code-behind if you handlers work via ViewModel. However, there is an alternative use GalaSoft.MvvmLight (link to download), in which have EventToCommand, supports parameter PassEventArgsToCommand.
Example of using:
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter">
<cmd:EventToCommand Command="{Binding FooCommand}"
PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
I think you can use both approaches. Your solution is simple, does not require the use of the any frameworks but uses code-behind, in this case it is not critical. One thing is certain, it is advisable not to keep ViewModel event handlers, use the command or store these handlers on View side.
Some new notes
I think, your way does not violate the principles of MVVM, all event handlers working with View, should be on the side of the View, the main thing - it's event handlers need to work with a ViewModel and have a dependency via an interface, but not directly with the UI.
The only principle MVVM that you break - is the mantra "no code" and this is not the main principle of MVVM. The main principles:
Split data Model of View
Application logic should not be tied to UI
Support testability code
Once the code-behind violate at least one of these principles, you must already see the alternatives to solve their problem.
Also, you can read opinions about it on this link:
WPF MVVM Code Behind

Related

What is the proper design for interacting with controls using MVVM where I need to do calculations based on XAML controls?

I am still a bit green in WPF. I am refactoring a sizable applications where all the work was done in the code behind. I am refactoring to use MVVM.
A bit about the application:
This application contains a single window, the single window and the pertinent pieces of the XAML are below:
<Grid>
<Border Style="{StaticResource ClipBorderStyle}" Name="ImageBorder">
<Grid Style="{StaticResource ClipGridStyle}" Name="ImageGrid">
<Image Name="KeyImage" Style="{StaticResource MainImageStyle}" Source="{Binding ImageSource}" Cursor="{Binding ImageCursor}"></Image>
<Canvas Name="KeyCanvas" Height="{Binding Source=KeyImage, Path=Height}" common:CanvasAssistant.BoundChildren="{Binding CanvasControls}"></Canvas>
</Grid>
</Border>
</Grid>
When the user clicks on the image, I drop a control onto the Canvas at the location where the user clicked. There can be many objects, and multiple control types. Currently I have a view model defined for each of the different control types and I keep an observable collection of them in a main view model. I am about half way through refactoring, and am realizing I still have a ton of work being done in the code behind, and am modifying the objects in the DataContext a lot. I am curious how I can move a lot of this out of the code behind into a more structured format (maybe into the view model, maybe another pattern). If it were simply modifying data, this would not be a problem, but in many cases I need to do transforms, and track the location on the image. The user can interact with the application using both their mouse and their keyboard (click to select an object, left arrow to move it, etc).
The Core Questions
When I have to to something like any of the following:
private Point TranslateImageCoordinatesToParentGrid(Point pointOnImage)
{
return KeyImage.TransformToVisual(ImageGrid).Transform(pointOnImage);
}
OR
private void Marker_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
var Marker = (Marker)sender;
if (Marker.IsMouseCaptured)
Marker.ReleaseMouseCapture();
}
OR
private void Marker_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
var Marker = (Marker)sender;
Marker.CaptureMouse();
_dataContext.SelectedObject = Marker;
Marker.Focus();
}
OR
private void controlMarker_OnMouseMove(object sender, MouseEventArgs e)
{
var controlMarker = (controlMarker)sender;
var controlDataContext = ((controlMarkerObject)controlMarker.DataContext);
if (!controlMarker.IsMouseCaptured) return;
var tt =
(TranslateTransform)
((TransformGroup)controlMarker.RenderTransform).Children.First(tr => tr is TranslateTransform);
var currentMousePos = e.GetPosition(ImageGrid);
// center mouse on controlMarker
currentMousePos -= controlDataContext.CenterOffsetFromTopLeft;
var v = _dataContext.Start - currentMousePos;
tt.X = _dataContext.Origin.X - v.X;
tt.Y = _dataContext.Origin.Y - v.Y;
var currentImagePos = TranslateImageGridCoordinatesToChildImage(currentMousePos + controlDataContext.TopLeftOffset);
controlDataContext.ImagePosition = currentImagePos;
}
Where is the appropriate place for this logic that interacts with both the view and the view model (and view models for the controls)?
Is the code behind the appropriate place for this?
Should I be using this eventing model where I defined the mouse events, or convert them to ICommands?
Is there a better/cleaner pattern to use for an application like this?
The single most important aspect of WPF that makes MVVM a great pattern to use is the data binding infrastructure. By binding properties of a view to a ViewModel, you get loose coupling between the VM and view and entirely remove the need for writing code in a ViewModel that directly updates a view. The data binding system also supports input validation, which provides a standardized way of transmitting validation errors to a view.
I didn't say that you have to honor the pattern, I just say that you do violate the MVVM pattern if you handle clicks in the code-behind of the view. That's a fact.
If you want to remove all this code from code behind I suggest to use Caliburn, or
System.Windows.Interactivity v4.0 for WPF:
Example with interactivity on your code:
<Button Content="Submit">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonUp">
<i:InvokeCommandAction Command="{Binding SubmitCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
When you need to work directly with UI controls from the view it's perfectly fine to write that code in the code-behind of the view. As a matter of fact that is where it belongs.
Since your ViewModel is already DataContext of the view you can easily get a reference to VM from the View's code-behind (var svm = DataContext as SomeViewModel) and update VM properties, call VM methods/function or do anything else that is in the domain of the ViewModel and defined within the ViewModel.

WPF + Caliburn Micro: how to catch Window Close event?

I am new in Caliburn Micro and learn it from this helloworld example. In the example there are only 2 views (.xaml) of type Application and UserControl, and 1 view model.
I avoid to use code behind. Therefore I have only view and view model. I want to know how to catch the window close event of my helloworld application so I can handle it in view model. My target: when user is going to close the app by pressing close [x] button on top-right corner the app gives feedback to the user.
I have read about IViewAware and IScreen, but I find no specific example related to my question.
A simple sample code for view and view model are highly appreciated. Thanks in advance.
PS. I use VS2013, C#.
What you can do is in your View you can attach Caliburn Micro by using
cal:Message.Attach="[Event Closing] = [Action OnClose($eventArgs)]"
So it will look like
<Window cal:Message.Attach="[Event Closing] = [Action OnClose($eventArgs)]">
And on your ViewModel you can just define a public method that says OnClose with CancelEventArgs as the parameter and you can handle it from there.
If your ViewModel inherits Screen, Caliburn Micro has some methods that you can override like
protected override void OnDeactivate(bool close);
this is called when a screen is closed or deactivated or
public override void CanClose(Action<bool> callback)
you can check CanClose usage here
If you are using the BootstrapperBase class you can use:
protected override void OnExit(object sender, EventArgs e)
You're looking for a way to bind an Event to a Command. The typical approach here is to use the EventToCommand behavior from MVVMLight.
Example usage (from the linked article):
<StackPanel Background="Transparent">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<command:EventToCommand
Command="{Binding Main.NavigateToArticleCommand,
Mode=OneWay,
Source={StaticResource Locator}}"
CommandParameter="{Binding Mode=OneWay}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<!--...-->
</StackPanel>
For your specific scenario, you are not using MVVMLight. Since that framework is open-source, you could copy the implementation of EventToCommand into your own project, or - more simply - you can use the InvokeCommandAction, which is part of the System.Windows.Interactivity.dll library, included with Expression Blend.
Example of InvokeCommandAction:
<TextBox x:Name="TicketNumber">
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<i:InvokeCommandAction Command="{Binding OpenTicketCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
Lastly, this entire MVVM dogma that you "can't have any code behind" has been shot down time | and | time again (that last link is particularly relevant). MVVM is supposed to be unit-testable, and separates the "View logic" from the "Business logic." The "Close" event is admittedly a bit of a gray area between View and Business logic. But, if you can write an event handler in your code behind, which invokes your ViewModel's appropriate method or command, and if you can unit test that code, then you're as good as gold. Don't worry about removing all traces of code-behind from your project.

Detect and handle Gestures in WP8 using MVVMLight

Problem
I'm currently trying to find a MVVMLight compatible way to use gestures in my WP8 app. Specifically I just want to detect a swipe/flick and bind it to a RelayCommand in my view model. Has there been any recent solution developed over the years that I'm unaware of?
Prior Research
I've done some research before hand, and the results I've come up with are mostly outdated or no longer exist. i.e:
Old Stackoverflow Question
Clarity Consulting Blog Post with non-existant code
toolkit:GestureListener from the Windows Phone Toolkit supports gestures but requires you to couple the ViewModel with the View.
Edit
Note: Found out that toolkit:GestureListener has been deprecated.
Joost Van Schaaik created such a behaviour on wp7: http://dotnetbyexample.blogspot.be/2011/03/simple-windows-phone-7-silverlight.html
He can be contacted on twitter by #localjoost
Found the answer to my question.
Instead of using toolkit:GestureListener, I found out that EventToCommand with ManipulationDelta or ManipulationCompleted works as well:
In XAML
<i:Interaction.Triggers>
<i:EventTrigger EventName="ManipulationDelta">
<Command:EventToCommand Command="{Binding SlideOutDeltaCommand, Mode=OneWay}" PassEventArgsToCommand="True"/>
</i:EventTrigger>
<i:EventTrigger EventName="ManipulationCompleted">
<Command:EventToCommand Command="{Binding SlideOutCompletedCommand, Mode=OneWay}" PassEventArgsToCommand="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
By passing in EventArgs to the ViewModel, you can detect whether a swipe gesture has been issued:
In ViewModel
Define RelayCommand
public RelayCommand<ManipulationDeltaEventArgs> SlideOutDeltaCommand
{
get;
private set;
}
Define Execute() Method
private void OnSlideDelta(ManipulationDeltaEventArgs e)
{
var delta = e.CumulativeManipulation.Translation;
//If Change in X > Change in Y, its considered a horizontal swipe
var isDeltaHorizontal = Math.Abs(delta.X) > Math.Abs(delta.Y) ? true : false;
}
Register your Command in ViewModel Constructor
public MainViewModel()
{
SlideOutDeltaCommand = new RelayCommand<ManipulationDeltaEventArgs>((e) => OnSlideDelta(e));
}

Issue with Interactivity in MVVMLight

Everyone, I am working on an MVVMLight app with WPF but my problem is that I want to fire the Loaded event once the user can load the page. For e.g. I have some navigation pages, so whenever the user clicks on any page, the PageLoaded event should be fired. But in my case it is not fired in the same way. I have a another page that's working perfectly fine. I don't know where I am making a mistake .
My Xaml code looks like this:
xmlns:vm="clr-namespace:Test.User.Facebook.ViewModel"
<UserControl.Resources>
<ResourceDictionary>
<vm:ViewModelLocator x:Key="Locator"/>
</ResourceDictionary>
</UserControl.Resources>
<UserControl.DataContext>
<Binding Source="{StaticResource Locator}" Path="FriendsList"/>
</UserControl.DataContext>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<cmd:EventToCommand Command="{Binding LoadedCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
And the ViewModel looks like this :
public RelayCommand LoadedCommand { get; private set; }
public FriendsListViewModel()
{
LoadedCommand = new RelayCommand(() => UserControlLoaded());
}
private void UserControlLoaded()
{
GetFriendsList();
}
This is not loaded when I go to this page. It doesn't fire the event. Someone can help me?
Thanks..
As far as I know the loaded event occurs before the interaction is stared. Therefore, EventToCommand cannot be used to handle the load event. In this case I usually create an event handler, that obtains the command from the DataContext. Then the CanExecute method of the command is evaluated and if it returns true the Execute method is called.
This pattern des not contradict the MVVM pattern and is a clean way out of the occasions when EventToCommand cannot be used. One drawback, however, is hat the CanExecute status is not bound to the enabled property automaticall. But this should not be a problem for the rare ocasions where you have to use this pattern, as when you have no interaction you usually don't have a visual.

Custom control toolbar need to invoke methods on my VM. How to do that?

Here is my question. I have UserControl that wraps group of buttons and it looks like this: (I show 2 buttons to illustrate what it is)
<Button Content="Cancel"
IsEnabled="{Binding State, Converter={StaticResource CancelEnabledConverter}}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:CallMethodAction MethodName="Cancel" TargetObject="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<Button Content="Delete"
IsEnabled="{Binding State, Converter={StaticResource DeleteEnabledConverter}}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:CallMethodAction MethodName="Delete" TargetObject="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
Now, when I place this UserControl on my view - I go by convention and create Cancel and Delete methods on my VM. So, view's XAML looks clean.
I want to create custom control that will have same functionality. Inside control I will have to handle onClick events for buttons and would like to call methods on VM just like it works now. What my code going to look like? I guess I need to access DataContext programmatically and call method by name somehow. I envision using control like so:
<myToolBar Mode="SaveExitDelete" />
So, this will be nice and short. But myToolBar will show 3 buttons and those buttons will call 3 methods(named by convention) on DataContext.
Any pointers?
EDIT
Main question is to how programmaticaly BIND command or method to button. I understand how commanding works, I'm using PRISM and it's got built-in DelegateCommand that I can use. I don't know how to create binding programmaticaly when I know Method name or command name.
Here is how I can see it working:
var button = new DitatToolbarButton();
button.Caption = "Cancel &\nExit";
button.Icon = new BitmapImage(new Uri("img_btn_cancel.png", UriKind.Relative));
button.Command = Binding("CancelCommand");
Obviously 3rd line is wrong but this is what I want. I want to be able to hardcode string that will contain name of command that I will expect VM to have.
Typically, this sort of thing would be done with Commands. In the case of a Button control, which already has the "Command" DependencyProperty, it's as simple as this:
<Button Command="{Binding DoItCommand}">Do it</Button>
and in your view-model class:
private ICommand DoItCommand
{
get
{
return new DelegateCommand(param => DoIt(param), param => CanDoIt(param));
}
}
where DoIt() and CanDoIt() are methods in your view-model and DelegateCommand is defined something like this:
public class DelegateCommand : ICommand
{
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
// ...
There's a decent example of this here. On a custom control, you can declare the Command DependencyProperty yourself. And on a framework control that does not have a Command DependencyProperty, you can use an attached property.

Categories

Resources