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 7882459
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T04:17:24+00:00 2026-06-03T04:17:24+00:00

I am a little confused on how to implement an event as a command

  • 0

I am a little confused on how to implement an event as a command in my particular situation. I want to honour MVVM, but don’t get how in this case.

I have a WPF ‘view’ – viewCustomerSearch. This has some text boxes on it, and when the user clicks ‘Search’ the results are populated in ListView. viewCustomerSearch is bound to viewmodelCustomerSearch, and it works great.

viewCustomerSearch is hosted on viewCustomer.

I want to know have viewCustomerSearch expose a custom command – CustomerSelectedCommand – that is ‘fired’ whenever the ListView in viesCustomerSearch is double clicked, and then handled by the viewmodel behind viewCustomer (which is viewmodelCustomer). This seems the theoretical MVVM pattern implemented correctly.

I have broken down the main problem into three smaller problems, but hopefully you can see they are all components of the same challenge.

FIRST PROBLEM: in order to have viewCustomerSearch expose a custom command I seem to have to put this code in viewCustomerSearch – which seems to ‘break’ MVVM (no code in the view code behind).

public readonly DependencyProperty CustomerSelectedCommandProperty = DependencyProperty.Register("CustomerSelectedCommand", typeof(ICommand), typeof(viewCustomerSearch));

public ICommand CustomerSelectedCommand
{
    get { return (ICommand)GetValue(CustomerSelectedCommandProperty); }
    set { SetValue(CustomerSelectedCommandProperty, value); }
}

SECOND PROBLEM (and this is the one that is really getting to me): Best explained by showing what I would do which breaks MVVM. I would have an event handler in the view:

private void lstResults_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    if (CustomerSelectedCommand != null) CustomerSelectedCommand.Execute(((ViewModels.viewmodelCustomerSearchResult)this.lstResults.SelectedItem).CustomerId);
}

Well … I know that you shouldn’t put this event handler here; rather it should have a Command to handle it in the viewmodelCustomerSearch. The two problems here are

  • because the ‘CustomerSelectedCommand’ ICommand is implemented in
    viewCustomerSearch, viewmodelCustomerSearch can’t see it to fire it.

  • I cannot see how to bind the MouseDoubleClick event to a command, instead of an event handler in the view code behind. I am reading about Attached Properties, but cannot see how they are to be applied here.

(Please note: I am using the common ‘RelayCommand’ elsewhere in the application; does this come into play here??)

THIRD PROBLEM: When I do use the non-MVVM way of firing the command in the code behind event handler, you can see that I am passing in the Selected Customer Id as an arguement into the command. How do I see that argument in the Command handler in viewCustomer? I create a new RelayCommand to handle it, but it seems the Execute method does not take arguments?

Given all of the above, I have to say that I do NOT personally subscribe to the ‘MVVM means NO CODE IN THE VIEW’. That seems crazy to me; code that is entirely to do with the view, and the view only, should not – IMHO – go in the viewmodel. That said, though, this does seem like logic-y stuff (not view stuff).

Many thanks for some insight. Sorry for the long post; trying to balance enough information for you to help me with ‘War and Peace’.

DS

  • 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-06-03T04:17:25+00:00Added an answer on June 3, 2026 at 4:17 am

    In your view you can add a “Command” property in xaml and bind it to your ViewModel’s command

    Command="{Binding CustomerSelectedCommand}"
    

    Parameters can be passed in multiple ways. Most of the time, I just have other items bound to my ViewModel and I can just use them directly. However there is also a property called CommandParameter, here’s an example of specifying it in XAML.

     CommandParameter="{Binding ElementName=txtPassword}"
    

    then in my ViewModel the definition of my Command looks like this

    private void UserLogonCommandExecute(object parameter)
    {
    ...
           var password_box = parameter as PasswordBox;
    ...
    }
    

    It sounds like you already know how to set up a RelayCommand in your ViewModel so I won’t go into that. I found How Do I: Build Data-driven WPF Application using the MVVM pattern helpful when I was getting started.

    Per Comment Request Command Property Example

    I’m just going to grab some working code, here’s how you add a Command property to a button in XAML.

    <Button Command="{Binding ConnectCommand}">
    //Your button content and closing </Button> here
    

    This assume you have set your DataContext to a ViewModel that has a Command called ConnectCommand. Here’s an example for ConnectCommand. You’ll need to replace the contents of ConnectCommandCanExecute and ConnectCommandExecute with whatever work you want done.

    public ICommand ConnectCommand
    {
        get
        {
            if (_connectCommand == null)
            {
                _connectCommand = new RelayCommand(param => ConnectCommandExecute(),
                                                   param => ConnectCommandCanExecute);
            }
            return _connectCommand;
        }
    }
    
    private bool ConnectCommandCanExecute
    {
        get { return !_instrumentModel.IsConnected; }
    }
    
    private void ConnectCommandExecute()
    {
        if (TcpSettingsChanged()) SaveTcpSettings();
        _instrumentModel.Connect(_tcpData);
    }
    

    RelayClass

    One part of making this simple is the RelayClass I have in one of my core library .dlls. I probably got this from one of the videos I watched. This can be cut and pasted in it’s entirety, there is nothing here you need to customize, except you’ll probably want to change the namespace this is in.

    using System;
    using System.Diagnostics;
    using System.Windows.Input;
    
    namespace Syncor.MvvmLib
    {
    public class RelayCommand : ICommand
    {
    private readonly Action<object> _execute;
    private readonly Predicate<object> _canExecute;
    
    public event EventHandler CanExecuteChanged
    {
      add
      {
        CommandManager.RequerySuggested += value;
      }
      remove
      {
        CommandManager.RequerySuggested -= value;
      }
    }
    
    public RelayCommand(Action<object> execute)
      : this(execute, (Predicate<object>) null)
    {
      this._execute = execute;
    }
    
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
      if (execute == null)
        throw new ArgumentNullException("execute");
      this._execute = execute;
      this._canExecute = canExecute;
    }
    
    [DebuggerStepThrough]
    public bool CanExecute(object parameter)
    {
      if (this._canExecute != null)
        return this._canExecute(parameter);
      else
        return true;
    }
    
    public void Execute(object parameter)
    {
      this._execute(parameter);
    }
    }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I get the concept behind a trie . But I get a little confused
I am a little bit confused trying to implement a very simple mutex (lock)
A little confused on how to do this since I haven't done this before,
I'm a little confused. The Apple Documentation states this: Note: For performance reasons, Cocoa
I am little confused with this code am looking for somenthing similar i have
I'm a little confused as to how this inversion of control ( IoC )
I'm considering using CouchDB for an upcoming site, but I'm a little confused as
I'm a little bit confused by this scenario: I have a class that implements
Ok, so I'm a little confused as to why I can't find this anywhere,
A little confused about this. If I speed up the processor, wouldn't it take

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.