简单说明如何在WPF中使用按钮单击来使用命令

时间:2015-04-29 07:25:40

标签: c# wpf

我是初学者,我正在尝试使用命令而不是Click =“显示”。

<Button Content ="Click Me!" Command = "{Binding ClickMeCommand}" />

我如何编写使用该命令的方法?假设我想显示“点击”这样的消息!单击按钮时在控制台中。我正在寻找易于理解的最简单的实现。我已经尝试过查看教程,但是它们使事情变得复杂,我很难理解。

1 个答案:

答案 0 :(得分:0)

一种方式是这样的: 创建ViewModel:

public class MainViewModel
{
    public MainViewModel()
    {

    }

    private ICommand clickMeCommand;
    public ICommand ClickMeCommand
    {
        get
        {
            if (clickMeCommand == null)
                clickMeCommand = new RelayCommand(i => this.ClickMe(), null);
            return clickMeCommand;
        }
    }

    private void ClickMe()
    {
        MessageBox.Show("You Clicked Me");
    }
}    

或者在构造函数中初始化它。

Command的第一个参数是单击将命令绑定到的按钮时执行的方法。第二个参数是根据逻辑启用/禁用按钮的方法。如果您希望始终启用该按钮,请设置:

在你的MainWindow代码后面,将MainViewModel设置为主窗口的datacontext。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        MainViewModel vm = new MainViewModel();
        InitializeComponent();
        this.DataContext = vm;
    }
}

和RelayCommand类(这只是ICommand接口的一个实现)。如果需要,可以使用ICommand的其他实现。

public class RelayCommand : ICommand
{
    readonly Action<object> execute;
    readonly Predicate<object> canExecute;

    public RelayCommand(Action<object> executeDelegate, Predicate<object> canExecuteDelegate)
    {
        execute = executeDelegate;
        canExecute = canExecuteDelegate;
    }

    bool ICommand.CanExecute(object parameter)
    {
        return canExecute == null ? true : canExecute(parameter);
    }

    event EventHandler ICommand.CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    void ICommand.Execute(object parameter)
    {
        execute(parameter);
    }
}