2013-10-30 125 views
1

我嘗試在MVVM模式下使用命令,但我不知道如何將命令「綁定」到特殊事件,例如, MouseUp或MouseEnter。這個怎麼做?MVVM - 關於特殊事件的命令

+2

使用'從MVVM光EventToCommand'行爲:http://www.galasoft.ch/mvvm/ – Bolu

+1

如果你不想使用MVVM Light,Blend具有類似的行爲。 – Tico

+0

@Tico - 請問您能解釋這種行爲以及如何使用它嗎? –

回答

3

首先,您應該在ViewModel中定義ICommnad屬性。

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> 
+0

如果我不使用ICOMMAND,relaycommand和just在各自視圖文件後面的代碼中聲明mousedown,那可以認爲是MVVM實現嗎? –

+2

@Sangram No.任何時候你使用代碼 - 這不是合適的MVVM。顯然,沒有'ViewModel'就不能有MVVM。 –

+0

@AnatoliiG,這是絕對的廢話 - MVVM的目的是爲了減少代碼背後,但說背後的代碼=不是MVVM是不正確的。請參閱http://channel9.msdn.com/blogs/kreekman/techdays-2010-understanding-the-model-view-viewmodel-pattern at 01:01:00 –

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; 
} 
}