在我的項目中,我想使用MVVM(&命令)。我已經開始瞭解ICommand的命令和實現。如何實現沒有參數的ICommand
我想創建不帶參數的ICommand
的實現。 (要觸發數據的數據/沖洗等的負荷 - 我不需要任何參數來做到這一點,所以它只是很自然地嘗試不帶參數創建命令)
這是我的代碼「M使用:
using System.Windows.Input;
public class NoParameterCommand : ICommand
{
private Action executeDelegate = null;
private Func<bool> canExecuteDelegate = null;
public event EventHandler CanExecuteChanged = null;
public NoParameterCommand(Action execute)
{
executeDelegate = execute;
canExecuteDelegate =() => { return true; };
}
public NoParameterCommand(Action execute, Func<bool> canExecute)
{
executeDelegate = execute;
canExecuteDelegate = canExecute;
}
public bool CanExecute()
{
return canExecuteDelegate();
}
public void Execute()
{
if (executeDelegate != null)
{
executeDelegate();
}
}
}
但我得到了正確的方式 ('XXX.YYYY.NoParameterCommand' does not implement interface member 'System.Windows.Input.ICommand.Execute(object)'
)
所以我想過做這樣反而不執行ICommand接口錯誤:
(由來自CanExecute
中缺少的參數和Execute
)
public class NoParameterCommand : ICommand
{
...omitted - no changes here...
public bool CanExecute(object parameter) //here I added parameter
{
return canExecuteDelegate();
}
public void Execute(object parameter) //and here
{
if (executeDelegate != null)
{
executeDelegate();
}
}
}
- IS就是一個很好的辦法做到這一點?
- 我應該使用其他方式嗎? (如果這樣,我該怎麼辦呢?)
這是一個很好的方法,當然除了把你的領域和事件初始化爲空是沒有意義的。默認情況下,字段爲空,事件背後的字段也爲空。 –
@KrisVandermotten這只是一種我無法擺脫的舊習慣。直到你指出它,甚至沒有意識到它在那裏。 :) – mishan