gpt4 book ai didi

c# - 绑定(bind)命令未执行

转载 作者:行者123 更新时间:2023-12-03 10:55:29 24 4
gpt4 key购买 nike

我的自定义命令没有被执行:

XAML:

<Button Command="{Binding NewServer}" Content="Save" />

XAML 背后的代码:
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();

DataContext = new ServerViewModel();
}
}

服务器 View 模型:
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 都没有被调用。我做错了什么?

最佳答案

public ICommand NewServer;

是一个字段。 WPF 不支持绑定(bind)到字段。只有属性。将其更改为
public ICommand NewServer {get;set;}

关于c# - 绑定(bind)命令未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15768173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com