0

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

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 都没有被调用。我做错了什么?

4

1 回答 1

4
public ICommand NewServer;

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

public ICommand NewServer {get;set;}
于 2013-04-02T15:34:52.017 回答