首页 > 解决方案 > 绑定命令的正确方法

问题描述

我正在尝试将我自己的命令绑定到一个按钮,但我没有尝试任何工作。

DataContext通过 XAML 绑定了窗口,但是当我尝试绑定到我的命令时,IntelliSense 没有看到它,并且没有执行该命令。我尝试通过代码隐藏进行绑定,但也遇到了相同的结果。

窗户是Binding这样的。

DataContext="{Binding Source={StaticResource mainViewModelLocator}, Path=Commands}"

mainViewModelLocator传递Commands类的新实例。

Commands班级:

public ICommand GradeCommand { get; set; }

public Commands()
{
    LoadCommands();
}

private void LoadCommands()
{
    GradeCommand = new CustomCommand(GradeClick, CanGradeClick);
}

private void GradeClick(object obj)
{
    MessageBox.Show("Test");
}

private bool CanGradeClick(object obj)
{
    return true;
}

ICommand

private Action<object> execute;
        private Predicate<object> canExecute;

        public CustomCommand(Action<object> execute, Predicate<object> canExecute)
        {
            this.execute = execute;
            this.canExecute = canExecute;
        }

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

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

        public void Execute(object parameter)
        {
            execute(parameter);
        }

标签: c#wpfmvvmdata-binding

解决方案


我想到了。我的 DataContext 绑定不起作用。我将其更改为:

xmlns:vm="clr-namespace:ProgramName.ViewModel"
    <Window.DataContext>
        <vm:Commands/>
    </Window.DataContext>

推荐阅读