绑定命令不会被执行

时间:2013-04-02 15:32:56

标签: c# wpf mvvm

我的自定义命令无法执行:

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。我做错了什么?

1 个答案:

答案 0 :(得分:4)

public ICommand NewServer;

是一个字段。 WPF不支持绑定到字段。只有属性。将其更改为

public ICommand NewServer {get;set;}