ReactiveUI:将 CanExecute 与 ReactiveCommand 一起使用 [英] ReactiveUI: Using CanExecute with a ReactiveCommand

查看:16
本文介绍了ReactiveUI:将 CanExecute 与 ReactiveCommand 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始在 Silverlight 项目中使用 ReactiveUI 框架,在使用 ReactiveCommands 时需要一些帮助.

I'm starting to work with the ReactiveUI framework on a Silverlight project and need some help working with ReactiveCommands.

在我的视图模型中,我有一些看起来大致像这样的东西(这只是一个简化的例子):

In my view model, I have something that looks roughly like this (this is just a simplified example):

public class MyViewModel : ReactiveObject
{
  private int MaxRecords = 5;

  public ReactiveCommand AddNewRecord { get; protected set; }

  private ObservableCollection<string> _myCollection = new ObservableCollection<string>();
  public ObservableCollection<string> MyCollection
  {
    get
    {
      return _myCollection;
    }

    set
    {
      _myCollection = value;
      raiseCollectionChanged("MyCollection");
    }
  }

  MyViewModel()
  {
    var canAddRecords = Observable.Return<bool>(MyCollection.Count < MaxRecords);
    AddNewRecord = new ReactiveCommand(canAddRecords);

    AddNewRecord.Subscribe(x => 
    {
       MyCollection.Add("foo");
    }
  }
}

canAddRecords 函数在第一次创建 ReactiveCommand 时被评估,但是当项目被添加到 MyCollection 时它不会被重新评估>.谁能告诉我一个很好的例子,说明如何绑定 ReactiveCommandcanExecute 属性,以便在这种情况下自动重新评估它?

The canAddRecords function is getting evaluated the first time the ReactiveCommand is created, but it's not getting re-evaluated when items are added to MyCollection. Can anyone show me a good example of how to bind the canExecute property of a ReactiveCommand so that it gets automatically re-evaluated in this situation?

推荐答案

实际上,有一个更好的方法可以做到这一点,将您的 ObservableCollection 更改为 ReactiveCollection(它继承自 ObservableCollection 但添加了一些额外的属性):

Actually, there's a better way to do this, change your ObservableCollection to ReactiveCollection (which inherits from ObservableCollection but adds some extra properties):

MyCollection = new ReactiveCollection<string>();

AddNewRecord = new ReactiveCommand(
    MyCollection.CollectionCountChanged.Select(count => count < MaxRecords));

现在的问题是,您不能覆盖 MyCollection,只能重新填充它(即 Clear() + Add()).让我知道这是否是一个交易破坏者,虽然它需要更多的工作,但也有一种方法可以解决这个问题.

The catch here now is though, you can't overwrite the MyCollection, only repopulate it (i.e. Clear() + Add()). Let me know if that's a dealbreaker, there's a way to get around that too though it's a bit more work.

这篇关于ReactiveUI:将 CanExecute 与 ReactiveCommand 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆