如何在UITableViewCells中处理绑定

时间:2017-01-09 11:28:48

标签: xamarin.ios reactiveui

我一直在使用ReactiveUI在应用上做一些工作。

我的问题在于UITableViews和重用单元格。我尝试使用ReactiveTableViewSource,但这似乎没有给我我想要的自定义级别(自定义页眉和页脚视图)。

所以我使用了UITableViewSource和UITableViewCell并实现了IViewFor。 然后我在单个细胞中进行结合。

这很好,但我担心重新绑定"每次重复使用一个单元时,都可以访问新的ViewModel。我相信我已经解决过这个问题,但我确信这是一个更好的方法。

代码I使用(仅相关位):

public partial class FlavourTableViewCell : UITableViewCell, IViewFor<MenuItemViewModel.FlavourSetItemViewModel>
{
    public MenuItemViewModel.FlavourSetItemViewModel ViewModel { get; set; }
    object IViewFor.ViewModel { get { return ViewModel; } set { ViewModel = (MenuItemViewModel.FlavourSetItemViewModel)value; } }

    List<IDisposable> bindings = new List<IDisposable> ();

    // Called when new data should be shown in cell
    internal void Update (MenuItemViewModel.FlavourSetItemViewModel data, MenuItemViewModel.FlavourSelectionEnum type)
    {
        ViewModel = data;

        // Clear old bindings
        if (bindings.Any ()) {
            bindings.ForEach (x => x.Dispose ());
            bindings.Clear ();
        }

        bindings.Add (this.Bind (ViewModel, x => x.IsSelected, view => view.SelectionButton.Selected));
    }
}

其他信息:

FlavourSetItemViewModel包含FlavourSetItemViewModel列表。我将尝试解释如下:

  • FlavourSetItemViewModel - 具有部分名称
    • FlavourSetItemViewModel - 具有项目名称
    • FlavourSetItemViewModel - 具有项目名称
    • FlavourSetItemViewModel - 具有项目名称
    • FlavourSetItemViewModel - 具有项目名称
  • FlavourSetItemViewModel - 具有部分名称
    • FlavourSetItemViewModel - 具有项目名称

1 个答案:

答案 0 :(得分:1)

你所做的事对我来说并没有错。您可以改进的是使用CompositeDisposable而不是IDisposable列表。

但您也可以尝试使用ReactiveTableViewSource使用自己的实现,然后覆盖GetViewForHeader以提供自己的标题视图。

然后,您可以将数据绑定到自定义表格视图源:

this.WhenAnyValue (view => view.ViewModel.Section1, view => view.ViewModel.Section2, (section1, section2) => new TableSectionInformation<TModel> [] {
    new TableSectionInformation<TModel, TReactiveTableViewCell> (section1, "section1cell", 44),
    new TableSectionInformation<TModel, TReactiveTableViewCell> (section2, "section2cell", 44)
})
.BindTo (tableViewSource, x => x.Data);

如果您使用的是动态数量的部分,则可以执行以下操作:

this.WhenAnyValue (view => view.ViewModel.TableSections)
    .Select (tableData => tableData.Select (section => new TableSectionInformation<TModel, TReactiveTableViewCell> (section, "cellIdentifier", 44)).ToArray ())
    .BindTo (tableViewSource, x => x.Data);

假设TableData是一个二维的排序列表。

请注意,在我的示例中,不会考虑对列表的更改。只更改属性(TableSections)本身。