Reignbeaux
Reignbeaux

Reputation: 1383

MVVM - Commands on special events

I try to use commands with the MVVM - Pattern and I don't know how to "bind" a command to a special event, e.g. MouseUp or MouseEnter. How to do this?

Upvotes: 1

Views: 987

Answers (4)

trinaldi
trinaldi

Reputation: 2950

Completing @AnatoliiG post here's an implementation and a sample usage of the RelayCommand class.

Code:

public class RelayCommand : ICommand
{
#region Fields
 
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
 
#endregion // Fields
 
#region Constructors
 
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
 
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
 
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
 
#region ICommand Members
 
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
 
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
 
public void Execute(object parameter)
{
_execute(parameter);
}
 
#endregion // ICommand Members
}

Usage:

// To use this class within your viewmodel class:
RelayCommand _myCommand;
public ICommand MyCommand
{
get
{
if (_myCommand == null)
{
_myCommand = new RelayCommand(p => this.DoMyCommand(p),
p => this.CanDoMyCommand(p) );
}
return _myCommand;
}
}

Upvotes: 0

Anatolii Gabuza
Anatolii Gabuza

Reputation: 6260

First you should define ICommnad property in your ViewModel.

public ICommand MouseUpCommand
{
    get 
    {
        if (this.mouseUpCommand == null)
        {
            this.mouseUpCommand = new RelayCommand(this.OnMouseUp);
        }

        return this.mouseUpCommand;
    }
}

private void OnMouseUp()
{
    // Handle MouseUp event.
}


You can find lot of ICommand implementations. One of them:

public class RelayCommand : ICommand
{
    public RelayCommand(Action<object> execute)
    {
         this._execute = execute;
         ...
    }

    ...

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
} 


Then add event trigger within which invoke your Command:

<i:EventTrigger EventName="MouseUp">
      <i:InvokeCommandAction Command="{Binding MouseUpCommand}"/>
</i:EventTrigger>

Upvotes: 3

jdehaan
jdehaan

Reputation: 19928

Look at WPF Binding UI events to commands in ViewModel.

For this you need System.Windows.Interactivity.dll which you can get from Nuget

Upvotes: 0

Krekkon
Krekkon

Reputation: 1347

Read the EventToCommand at the following page, please

Upvotes: 0

Related Questions