Reactive UI将Observable合并到ObservableAsPropertyHelper

时间:2015-02-17 22:00:30

标签: c# reactiveui

我正在尝试在几个Observable上合并多个ReactiveList来创建ObservableAsPropertyHelper

public class Model : ReactiveObject {
    ReactiveList<int> IngredientsEntities;
    // ...
    public int CostOfIngredients(...) { ... }
}

public class ViewModel : ReactiveObject {

    public Model Promotion;

    private ReactiveList<int> ingredientsQuantities;
    private ObservableAsPropertyHelper<int> cost;

    public Dictionary<..., ...> Ingredients;

    public int Cost {
        get { return cost.Value; }
    }

    public ViewModel() {
        // ...

        var ingredientsObservables = new[]
        {
            ingredientsQuantities.ItemChanged.Select(_ => Unit.Default),
            ingredientsQuantities.ShouldReset.Select(_ => Unit.Default),
            Promotion.IngredientsEntities.ItemChanged.Select(_ => Unit.Default),
            Promotion.IngredientsEntities.ShouldReset.Select(_ => Unit.Default),
        };
        Observable.Merge(ingredientsObservables)
            .Select(_ => promotion.CostOfIngredients(Ingredients))
            .ToProperty(this, x => x.Cost, out cost);

        Observable.Merge(ingredientsObservables)
            .Subscribe(_ =>
            {
                this.Log().Info("Ingredients change detected");
            });

    }
}

日志消息会触发,但CostOfIngredients永远不会被调用,cost仍然是null。我在这里做错了吗?

编辑:

我修改了ViewModel,现在可行了:

public class ViewModel : ReactiveObject {
    private int cost;
    public int Cost {
        get { return cost; }
        set { this.RaiseAndSetIfChanged(ref cost, value); }
    }

    // ...

   public ViewModel() {
        // ...
        var ingredientsObservables = new[]
            {
                ingredientsQuantities.ItemChanged.Select(_ => Unit.Default),
                ingredientsQuantities.ShouldReset.Select(_ => Unit.Default),
                Promotion.IngredientsEntities.ItemChanged.Select(_ => Unit.Default),
                Promotion.IngredientsEntities.ShouldReset.Select(_ => Unit.Default),
            };
            Observable.Merge(ingredientsObservables)
                .Subscribe(_ => Cost = promotion.CostOfIngredients(Ingredients));

   }
}

我的理解是Select(_ => Unit.Default)Observable创建了一个永不改变的Unit.Default,因此永远不会再调用任何Select

1 个答案:

答案 0 :(得分:3)

我认为您的问题是您使用ItemChanged - 只有在您启用了项目跟踪时才会触发,并且只有在您的集合中的项目发生更改时才会触发(即myList[3].SomeProperty = "bar";)。您可能需要Changed,这将涵盖所有内容。