繼續沿着MVVM的路徑,我來到了按鈕命令。經過相當多的試驗和錯誤,我終於有了一個使用ICommand
的Button_Click
命令的工作示例。如何識別點擊了哪個按鈕? (MVVM)
我的問題是,現在我有一個通用的事件,我不能得到哪個按鈕被點擊應用一些邏輯。在我的例子中,我沒有使用任何可以獲得Sender
信息的地方。通常這樣使用下面的東西RoutedEventArgs
:
Button button = (Button)sender;
所以這就是我到目前爲止。
的ICommand
類:
public class CommandHandler : ICommand
{
private Action _action;
private bool _canExecute;
public CommandHandler(Action action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action();
}
}
和代碼,以使動作:
private ICommand _clickCommand;
public ICommand ClickCommand => _clickCommand ?? (_clickCommand = new CommandHandler(MyAction, _canExecute));
public ViewModelBase()
{
_canExecute = true;
}
public void MyAction()
{
//Apply logic here to differentiate each button
}
而XAML,
<Button Command="{Binding ClickCommand}" Style="{StaticResource RedButtonStyle}">MyButton</Button>
我怎麼會去識別哪些按鈕在將相同的命令綁定到其他按鈕時被點擊?
只是好奇,爲什麼不只是使用* 2 * ICommands? –
@XanderLuciano,我只是認爲應用一些標準diffirenitate按鈕的方法是做到這一點。乾杯 – KyloRen
夠公平的!我剛剛在一個月前開始使用MVVM,所以我明白需要調整思路的努力。祝你好運! –