ICommand 的 CanExecute 方法可以动态重新定义吗?

发布于 2024-08-24 15:25:46 字数 574 浏览 4 评论 0原文

我一直无法找到有关此问题的任何信息,这似乎可能是解决 p我的最后一个未回答的问题。然而,我认为现在这确实应该是一个单独的问题。

我想知道是否有一种方法可以动态地重新定义 ICommand 派生类的 CanExecute 方法。我对 .NET 还很陌生,也许这真的很明显,但我还没能弄清楚。这里有人以前做过这种事吗?如果我能让这个工作正常,这对我的特定问题非常有用。基本上,我希望能够循环 ICommand 列表,并通过用不同的实现替换它们的实现来强制它们的所有 CanExecute 方法返回 true。

通过搜索“.NET代码替换”之类的内容,我找到了这篇文章 ,但我希望有一种稍微简单的方法。不过,如果必须的话,我会这么做。

I've been unable to find any info on this, which seems like it could be the only way to solve a past unanswered question of mine on SO. However, I think this should really be a separate question now.

I am wondering if there is a way to dynamically redefine an ICommand-derived class's CanExecute method. I'm still new to .NET and perhaps this is really obvious, but I haven't been able to figure it out. Has anyone here done this sort of thing before? If I could get this working, it would be very useful for my particular problem. Basically, I want to be able to loop over a List of ICommands and force all of their CanExecute methods to return true by replacing their implementation with a different one.

From searching for things like ".NET code replacement", I found this article, but I was hoping that there's a slightly simpler approach. However, if I have to, I'll do it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

救赎№ 2024-08-31 15:25:46

让您的 ICommand 派生类调用委托来确定 CanExecute 是否可以完成,这样您就可以公开委托的 setter 并在运行时更改它

作为一个简单的示例:

public class MyCommand : ICommand
{
  private Func<object, bool> _canExecuteMethod;

  public void SetCanExecuteMethod(Func<object, bool> canExecuteMethod)
  {
    //check delegate not null if need be
    _canExecuteMethod = canExecuteMethod;
  }

  public bool CanExecute(object parameter)
  {
    //check for null delegate - maybe return false if it's null....
    return _canExecuteMethod(parameter);
  }

  //....other codefor ICommand

}

您还可以仅使用 Func<如果您不需要额外的数据来做出决定,则为委托使用 /code> 。如果需要,委托也可以在其他地方公开,并且只需从 ICommand 类调用

Have your ICommand derived class call a delegate to determine if CanExecute can be done, this way you can expose a setter for the delegate and change it at runtime

As a simple example:

public class MyCommand : ICommand
{
  private Func<object, bool> _canExecuteMethod;

  public void SetCanExecuteMethod(Func<object, bool> canExecuteMethod)
  {
    //check delegate not null if need be
    _canExecuteMethod = canExecuteMethod;
  }

  public bool CanExecute(object parameter)
  {
    //check for null delegate - maybe return false if it's null....
    return _canExecuteMethod(parameter);
  }

  //....other codefor ICommand

}

You could also utilize just Func<bool> for the delegate if you don't need the extra data to make the decision. Also the delegate can be exposed elsewhere if required and just called from the ICommand class

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文