1

我尝试将命令与 MVVM - Pattern 一起使用,但我不知道如何将命令“绑定”到特殊事件,例如 MouseUp 或 MouseEnter。这个怎么做?

4

4 回答 4

3

首先,您应该ICommnadViewModel.

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

        return this.mouseUpCommand;
    }
}

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


你可以找到很多ICommand实现。其中之一:

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

    ...

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


然后添加事件触发器,在其中调用您的Command

<i:EventTrigger EventName="MouseUp">
      <i:InvokeCommandAction Command="{Binding MouseUpCommand}"/>
</i:EventTrigger>
于 2013-10-30T12:10:03.913 回答
0

请阅读下一页的EventToCommand

于 2013-10-30T12:11:16.520 回答
0

查看WPF 将 UI 事件绑定到 ViewModel 中的命令

为此,您需要System.Windows.Interactivity.dllNuget获得

于 2013-10-30T12:12:56.390 回答
0

在此处完成@AnatoliiG 帖子是RelayCommand该类的实现和示例用法。

代码:

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
}

用法:

// 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;
}
}
于 2013-10-30T12:28:31.660 回答