开发者

How to achieve clean code-behind files?

开发者 https://www.devze.com 2022-12-21 07:34 出处:网络
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 lo

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 Co开发者_开发问答mmand 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 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 :-)*


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消