首页 > 解决方案 > 如何使用 ReactiveUI 和 DynamicData 链接 SourceList 观察?

问题描述

如果术语关闭,请道歉;我是一名 iOS 开发人员,必须使用 Xamarin.iOS 来开发应用程序。我正在使用带有 DynamicData 和 MVVM 架构的 ReactiveUI。总的来说,我对 RxSwift 和 FRP 概念相当满意。SourceList<MyThing>根据文档,我有一个发布 a 的模型,如下所示:

// Property declarations
private readonly SourceList<MyThing> Things;
public IObservableCollection<MyThing> ThingsBindable { get; }

// Later, in the constructor...
Things = new SourceList<MyThing>();
// Is this of the right type?
ThingsBindable = new ObservableCollectionExtended<MyThing>();
Things
    .Connect()
    .Bind(ThingsBindable)
    .Subscribe();

我可以.BindTo()在我的视图(即 iOS 领域的 ViewController)中成功使用来获取 UITableView 以在模型更改时进行更新:

Model
    .WhenAnyValue(model => model.ThingsBindable)
    .BindTo<MyThing, MyThingTableViewCell>(
        tableView,
        new NSString("ThingCellIdentifier"),
        46, // Cell height
        cell => cell.Initialize());  

我不想直接绑定到模型,而是让 ViewModel 订阅和发布(或以其他方式代理)这个SourceList<MyThing>,或者这个的可绑定版本,以便 View 只使用 ViewModel 属性。在文档SourceList中声明private;我不确定这里的最佳实践:我是否将其公开并Connect()在 ViewModel 中执行?或者有没有办法传递IObservableCollection<MyThing> ThingsBindable从 ViewModel 公开暴露的内容?我也不相信这ObservableCollectionExtended<MyThing>是 Bindable 属性的正确类型,但它似乎有效。

我尝试了,等的各种组合.ToProperty(),并在 ViewModel 中制作了 View-binding Observable 的一个版本,但无济于事,现在我只是将自动完成功能扔到墙上,看看有什么效果。任何方向表示赞赏。TIA。.Bind().Publish()

标签: iosxamarin.iosdynamic-datareactiveuixamarin.ios-binding

解决方案


我认为这是初学者的误解。这就是我想要的工作方式;也许它会帮助其他 Xamarin.iOS/ReactiveUI/DynamicData 新手。

在我的模型中,我声明了私有SourceList和公开的IObservableList<MyThing>

private readonly SourceList<MyThing> _ModelThings;
public IObservableList<MyThing> ModelThings;

然后在我的构造函数中实例化它们:

_ModelThings = new SourceList<MyThing>();
ModelThings = _Things.AsObservableList();

在我的 ViewModel 中,我声明了一个本地ObservableCollectionExtended<MyThing>并将其绑定到模型的公共属性:

public ObservableCollectionExtended<MyThing> ViewModelThings;

// Then, in the constructor:
ViewModelThings = new ObservableCollectionExtended<MyThing>();

model.ModelThings
    .Connect()
    .Bind(ViewModelThings)
    .Subscribe();

在我的 ViewController 中,我将表绑定到ViewModel.ViewModelThings,如问题所示。如果我想拥有另一个级别的模型,我可以简单地穿过Model.ModelThings.Connect().Bind()降低,正如格伦在他的评论中暗示的那样。

FWIW,我发现Roland 的博客(特别是 Observable Lists/Caches 部分)比 GitHub 文档更容易理解。


推荐阅读