首页 > 解决方案 > WPF 命令绑定与返回 bool 的方法

问题描述

我有两种方法几乎可以完成两件事:

    public static void ShowThing()
    {
        // code..
    }

    public static bool TryShowThing()
    {
        if(condition)
        {
            // same code above..
            return true;
        }
        return false;
    }

目前我正在将按钮的命令绑定到该void方法,它会做它应该做的事情。问题是现在我正在清理代码并避免耦合,我想将按钮绑定到bool方法,但这不起作用。

Command={Binding BooleandReturningMedhod}甚至允许在 xaml 中使用吗?

显然,互联网上以前没有人遇到过这个问题,所以我想我在这里遗漏了一些东西......

标签: c#wpfxaml

解决方案


您不能直接绑定到方法。

我认为你真正想要实现的是这样的

代码:

ShowThingCommand { get; } = new RelayCommand((o) => ShowThing(),(o) => condition)

中继命令:

public class RelayCommand : ICommand    
{    
    private Action<object> execute;    
    private Func<object, bool> canExecute;    

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

    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)    
    {    
        this.execute = execute;    
        this.canExecute = canExecute;    
    }    

    public bool CanExecute(object parameter)    
    {    
        return this.canExecute == null || this.canExecute(parameter);    
    }    

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

XAML:

<Button Command={Binding ShowThingCommand } />

重要的部分是CanExecute方法,当它返回falseButton被禁用时


推荐阅读