且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 WPF 用户控件中绑定到路由事件的命令

更新时间:2022-06-22 02:42:15

这段代码展示了如何调用命令:命令处理程序

Hi this piece of code shows how to call command: Command handler

public class CommandHandler : ICommand
{
    public CommandHandler(Action<object> action,Func<object,bool> canexecute)
    {
        _action = action;
        _canExecute = canexecute;

    }
    Action<object> _action;
    Func<object, bool> _canExecute;

    public bool CanExecute(object parameter)
    {
       return _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged;

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

视图模型

public class MainViewModel
{
    private CommandHandler _buttonCommand;

    public CommandHandler ButtonCommand
    {
        get
        {
            return _buttonCommand ?? (_buttonCommand = new CommandHandler((param) => OnButtonCommand(param),(param)=>true));
        }
    }

    private void OnButtonCommand(object obj)
    {
        //DO things here whatever you want to do on Button click
    } 
}

查看

<Button Command="{Binding ButtonCommand}" Content="ok"/>

您需要向 CommandHandler 构造函数传递两个参数,一个是要在 Command 上触发的 Action,第二个参数是必须返回 bool 的 func.如果 func 评估为真,则命令的动作被触发.并且动作中的参数和 func 是你将绑定到 CommandParameter 在我上面的例子中它将为空,因为我没有绑定 CommandParameter.我希望这会有所帮助.

you need to pass two parameters to CommandHandler Constructor one is Action that you want to fire on Command and second param is func that must return bool. If func evaluates to true only then the Action of Command is fired.And the param in action and func is what you will bind to the CommandParameter in my case above it will be null as I havent binded the CommandParameter.I hope this will help.