Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 625993
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T19:22:13+00:00 2026-05-13T19:22:13+00:00

Working with WPF it is good practice to keep your xaml.cs code behind files

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T19:22:13+00:00Added an answer on May 13, 2026 at 7:22 pm

    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 :-)*

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 450k
  • Answers 450k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer i get around this by creating class which carry the… May 15, 2026 at 8:30 pm
  • Editorial Team
    Editorial Team added an answer You misspelled it. Your constructor is spelled BaseSqlRe sp ository.… May 15, 2026 at 8:30 pm
  • Editorial Team
    Editorial Team added an answer jQuery selectors that have more than one match will return… May 15, 2026 at 8:30 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.