c# - 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 中使用吗?
显然,互联网上以前没有人遇到过这个问题,所以我想我在这里遗漏了一些东西......
解决方案
您不能直接绑定到方法。
我认为你真正想要实现的是这样的
代码:
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
方法,当它返回false
你Button
被禁用时
推荐阅读
- java - PlayerJoinEvent - 创建欢迎消息 Spigot 1.12.2 (Java)
- swift - Swift String 值转换成奇怪的 Date 值
- r - 是否有 R 函数可以为条形图制作箱?
- javascript - react.js 中是否有用于 agora.io 的 UI 包
- php - 如何在 laravel api 或颤振视图上转换 yyyy-mm-ddthh:mm:ss.sssz?
- asp.net-core-mvc - 在 ASP.NET Core MVC 的 PartialView 中使用 Ajax 后选择模式为空
- clojure - 如何用 Leiningen 运行图书馆的`main`?
- sql - 从邀请表中查找最后一行
- java - 只是 JTextField 中的数字
- javascript - 如何在同一页面上多次添加相同的轮播?