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

标签 c# wpf mvvm

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

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/

相关文章:

C# 谷歌翻译,不带 api 且带 unicode

c# - 检查 Excel 工作表中是否存在列

c# - 将数据行添加到预定义索引处的数据表

c# - 如果以前的记录在 ItemsSource 集合中没有匹配项,则 WPF ComboBox 绑定(bind)有效,如果有则失败

c# - Caliburn.micro - 在另一个 View 模型中通知属性更改的 View 模型

c# - 如何在C#/MVVM应用程序中解决无法解释的ObjectDisposedExceptions?

c# - 数据网格:用户无法编辑或选择行

c# - 对 Mac 上的 Xamarin Studio 的 MVVM 交叉支持

c# - 绑定(bind)组合框到字典,下拉列表显示键和值

c# - XAML设计器因自注册ViewModel而崩溃