[英]Bound command doesn't get executed
我的自定義命令無法執行:
XAML:
<Button Command="{Binding NewServer}" Content="Save" />
XAML的代碼背后:
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
DataContext = new ServerViewModel();
}
}
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");
}
}
NewServerCommand:
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都不被調用。 我做錯了什么?
public ICommand NewServer;
是一個領域。 WPF不支持綁定到字段。 僅屬性。 更改為
public ICommand NewServer {get;set;}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.