我的自定义命令没有被执行:
XAML:
<Button Command="{Binding NewServer}" Content="Save" />
XAML 背后的代码:
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
DataContext = new ServerViewModel();
}
}
服务器视图模型:
public class ServerViewModel : DependencyObject {
public ICommand NewServer;
private readonly Dispatcher _currentDispatcher;
public ServerViewModel() {
NewServer = new NewServerCommand(this);
_currentDispatcher = Dispatcher.CurrentDispatcher;
}
public void SaveNewServers() {
throw new NotImplementedException("jhbvj");
}
}
新服务器命令:
public class NewServerCommand : ICommand {
public event EventHandler CanExecuteChanged {
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
private readonly ServerViewModel _vm;
public NewServerCommand(ServerViewModel vm) {
_vm = vm;
}
public bool CanExecute(object parameter) {
Dispatcher _currentDispatcher = Dispatcher.CurrentDispatcher;
Action dispatchAction = () => MessageBox.Show("asd");
_currentDispatcher.BeginInvoke(dispatchAction);
return true;
}
public void Execute(object parameter) {
_vm.SaveNewServers();
}
}
CanExecute 和 Execute 都没有被调用。我做错了什么?