有关如何在 WPF 中使用带有按钮单击的命令的简单说明



我是一个初学者,我正在尝试使用命令而不是Click="Display"。

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

我将如何编写使用该命令的方法?假设我想在单击按钮时在控制台中显示类似"单击!"的消息。我正在寻找易于理解的最简单的实现。我试过看教程,但它们使事情过于复杂,我很难理解。

一种方法是这样的:创建您的视图模型:

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

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

命令

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

在 MainWindow 代码隐藏中,将 MainViewModel 设置为主窗口的数据上下文。

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

最新更新