Marek M.
Marek M.

Reputation: 3951

Bound command doesn't get executed

My custom command doesn't get executed:

XAML:

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

XAML's code behind:

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();
    }
}

Neither CanExecute, nor Execute are called. What have I done wrong?

Upvotes: 0

Views: 85

Answers (1)

Fede
Fede

Reputation: 44038

public ICommand NewServer;

is a field. WPF does not support binding to fields. only Properties. Change that to

public ICommand NewServer {get;set;}

Upvotes: 4

Related Questions