views:

113

answers:

3

Working with WPF it is good practice to keep your xaml.cs code behind files small and clean. The MVVM pattern helps achieving this goal through Data Bindings and Command Bindings where any business logic is handled in the ViewModel classes.

I am using the principles of the MVVM pattern and my code-behind files are rather nice and clean. Any button click events are handled using Command Bindings, and there are a few more controls that also supports Command Binding. However, there are several events on controls that does not have the Command and CommandParameter properties, and hence I see no direct way for using bindings. What is the best approach for getting rid of logic in the code-behind files for such events? E.g. handling mouse events inside a control.

A: 

I have solved this with the following strategy, but I don't know if this is the ideal solution.

For the events that does not support Command Binding I handle the event itself in the code behind file, but I don't actually do any business logic there. Then the related ViewModel class has a function to handle the event, so the code-behind event handler calls the corresponding function of its ViewModel class.

E.g. I have some mouse events. Let's look at the MouseDown event on a Canvas. This will trigger an event handler in the code-behind, and the event handler will simply pass the call to the ViewModel. In this case all I need to know is which mouse button is pressed, and what's the current possition, so I don't pass the MouseEventArgs:

private void CanvasMouseDown(object sender, MouseButtonEventArgs e)
{
    var mousePositionX = e.GetPosition(_myCanvas).X;
    var mousePositionY = e.GetPosition(_myCanvas).Y;
    _vm.MouseDown(e.ChangedButton, mousePositionX, mousePositionY);
}

The ViewModel then has a MouseDown function which is where I actually handle the event:

public void MouseDown(MouseButton button, double mousePositionX, mousePositionY)
{
    switch (button)
    {
        case MouseButton.Left:
            // Do something 
            break;
        case MouseButton.Right:
            // Do something 
            break;
        case MouseButton.Middle:
            // Do something 
            break;
    }

    _mousePositionX = mousePositionX;
    _mousePositionY = mousePositionY;
}

Does this sound like a reasonable way of getting code out of your code behind? Any better solutions? Best practice?

stiank81
+3  A: 

A nice approach for this is to use an attached behaviour. The behaviour itself can hook the event you need and fire the appropriate command with the parameters you want. It's essentially the same code, but it just remove it from your code behind and lets you express your intent purely in XAML.

There are several example behaviours on CodePlex, or a here's a basic sample that executes a command:

using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

/// <summary>
/// Trigger action to execute an ICommand command
/// </summary>
public class ExecuteCommand : TriggerAction<FrameworkElement>
{
    #region Dependency Properties

    /// <summary>
    /// Command parameter
    /// </summary>
    public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(ExecuteCommand), new UIPropertyMetadata(null, OnCommandParameterChanged));

    /// <summary>
    /// Command to be executed
    /// </summary>
    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(ExecuteCommand), new UIPropertyMetadata(null, OnCommandChanged));

    #region Public Properties

    /// <summary>
    /// Gets or sets the command
    /// </summary>
    public ICommand Command
    {
        get
        {
            return (ICommand)this.GetValue(CommandProperty);
        }

        set
        {
            this.SetValue(CommandProperty, value);
        }
    }

    /// <summary>
    /// Gets or sets the command parameter
    /// </summary>
    public object CommandParameter
    {
        get
        {
            return (object)this.GetValue(CommandParameterProperty);
        }

        set
        {
            this.SetValue(CommandParameterProperty, value);
        }
    }
    #endregion

    /// <summary>
    /// Executes the command if it is not null and is able to execute
    /// </summary>
    /// <param name="parameter">This argument not used</param>
    protected override void Invoke(object parameter)
    {
        if (this.Command != null && this.Command.CanExecute(this.CommandParameter))
        {
            this.Command.Execute(this.CommandParameter);
        }
    }

    /// <summary>
    /// Called on command change
    /// </summary>
    /// <param name="oldValue">old ICommand instance</param>
    /// <param name="newValue">new ICommand instance</param>
    protected virtual void OnCommandChanged(ICommand oldValue, ICommand newValue)
    {
    }

    /// <summary>
    /// Called on command parameter change
    /// </summary>
    /// <param name="oldValue">old ICommand instance</param>
    /// <param name="newValue">new ICommand instance</param>
    protected virtual void OnCommandParameterChanged(object oldValue, object newValue)
    {
    }

    /// <summary>
    /// Called on command parameter change
    /// </summary>
    /// <param name="o">Dependency object</param>
    /// <param name="e">Dependency property</param>
    private static void OnCommandParameterChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        ExecuteCommand invokeCommand = o as ExecuteCommand;
        if (invokeCommand != null)
        {
            invokeCommand.OnCommandParameterChanged((object)e.OldValue, (object)e.NewValue);
        }
    }

    /// <summary>
    /// Called on command change
    /// </summary>
    /// <param name="o">Dependency object</param>
    /// <param name="e">Dependency property</param>
    private static void OnCommandChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        ExecuteCommand invokeCommand = o as ExecuteCommand;
        if (invokeCommand != null)
        {
            invokeCommand.OnCommandChanged((ICommand)e.OldValue, (ICommand)e.NewValue);
        }
    }        
    #endregion
}

}

You can then use the System.Windows.Interactivity namespace (the assembly is included with Blend 3) to hook the event and fire the command as follows:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseLeftButtonUp">
        <triggers:ExecuteCommand Command="{Binding MyCommand}" CommandParameter="MyParameter" />
    </i:EventTrigger>
</i:Interaction.Triggers>

For more complicated events with multiple parameters you may need to create a specific Behaviour, rather than using a generic one like the example above. I generally prefer to create my own type to store parameters, and map to it, rather than having a specific EventArgs requirement in my ViewModel.

*One thing I should add is that I'm definately not a "0 code in the Code Behind" kind of guy, and I think enforcing this religiously is missing the point of MVVM somewhat. As long as the code behind contains no logic, and therefore nothing that really need to be under test, then I can live with some small pieces of code behind for "bridging the gap" between View and ViewModel. This is also sometimes necessary if you have a "smart view", as I generally call it, such as a browser control, or something you need to commmunicate with from your ViewModel. Some people would get pitchforks out for even suggesting such a thing, that's why I left this bit until last and answered your question first :-)*

Steven Robbins
Thx! Did not know about this. In the case of mouse event can I attach something like MouseEventArgs as CommandParameter? And then have a custom command triggered for each time there is e.g. a MouseDown event on some control?
stiank81
If you want to use the eventargs then you're going to want to use a different behaviour. There is a MouseBehavior in the CodePlex project I linked to that might fit the bill.
Steven Robbins
Thx. Will look into it!
stiank81
In your update I assume you mean "0 code in Code Behind kind of guy"? :-) Your opinions sounds reasonable. I can live with some code in code behind as long as we work for bringing the logic out of the code behind - which is what my answer suggests.
stiank81
Hehe, yes, that's what I meant.. thanks for the spot :-)
Steven Robbins
+1 for: "I'm definately not a "0 code in the Code Behind" kind of guy, and I think enforcing this religiously is missing the point of MVVM somewhat" - MVVM has nothing to do with keeping a 'clean' code behind - there is nothing clean about it - it just happens that often when using MVVM little code behind is used.
Mrk Mnl
+1  A: 

Hi Stian,

My advice would be controversial. Don't do this. I.e. do this, but be very careful. One of the main goals of MVVM is to simplify development. If it makes you write code, that is hard to understand and support - you've chosen wrong path.

Please, don't get me wrong. I'm not saying "write everything in code behind". I'm saying - it's totally fine to have some code in the code behind if this code simplifies understanding. And don't think you break pattern. Patterns are just recommendations...

Anvaka
I'm all with you on the "Patterns are just recommendations" point, but I don't agree that I shouldn't do this. Having a lot of code in your code behind feels dirty, and it is difficult to unit test. See my answer for an idea on how to handle events in code behind, but passing them to a ViewModel. This makes the logic testable even if the event itself is handled in the code behind. Make sense? +1 anyway for giving your opinion..!
stiank81
Yes, Stian, it's totally makes sense. Having a lot of code is evil. I tried to say that spending a lot of time removing last piece of code from code behind is not the less evil...
Anvaka