MvxTableViewCell 加载一个空视图

MvxTableViewCell loads an empty view

我需要一个自定义 iOS TableView,其中包含不同的单元格,具体取决于项目类型。看起来很简单,只需在 TableViewSource 构造函数中定义布局,它是 MvxTableViewSource 的子项。注册是这样的:

public TableViewSource(UITableView tableView, List<ItemHolder> sections) : base(tableView) {
    tableView.RegisterClassForCellReuse(typeof(MyCell), "MyCellId");
    [Registering further types here]
}

为了处理部分,我创建了一个 ItemHolder 来定义部分和部分 header/footer 中的项目。那部分工作得很好。

在 GetOrCreateCellFor 中,我根据给定项目的类型使用默认值 DequeueReusableCell。但是,如果我像上面那样注册单元格,则会绘制一个空单元格。

我的cell使用XIB+Backing class(基于MvxTableViewCell)方式,理论上应该可以正常工作。如果我使用它的 Nib 属性,并使用 RegisterNibForCellReuse,则会绘制内容(但是行高错误,并且不会发生绑定,因为它是在支持 class 中定义的) .

class 看起来像这样:

public partial class MyCell : MvxTableViewCell
{
    public static readonly NSString Key = new NSString("MyCell");
    public static readonly UINib Nib = UINib.FromName("MyCell", NSBundle.MainBundle);

    protected MyCell(IntPtr handle) : base(handle)
    {
        this.DelayBind(() =>
        {
            var binding = this.CreateBindingSet<MyCell, object>();
            binding.Bind(this.TextView.Text).To(vm => vm.GetType().Name).WithConversion(new StringFormatConverter(), "Unknown cell type: {0}");
            binding.Apply();
        });
    }

    public static MyCell Create()
    {
        return (MyCell)Nib.Instantiate(null, null)[0];
    }
}

在 XIB 中,我使用 AutoLayout 设置了一个 UILabelView,它有一个名为 TextView 的 Outlet。

所以基本上,如果我通过 class 本身添加它,它根本不起作用。如果我使用 Nib,那么布局可以工作,但是没有绑定、数据上下文等,从技术上讲我的逻辑已经不存在了。

我是不是哪里做错了,或者这根本不起作用?

立即突出的一件事是定义绑定的方式。你不需要绑定TextView.Text,你只需要传入TextView:

binding.Bind(TextView).To(vm => vm.GetType().Name).WithConversion(new StringFormatConverter(), "Unknown cell type: {0}");

该修复可能会让一切为您服务。否则,这就是我在 MvvmCross 中对 XIB 文件中定义的单元格布局有用的方法:

1.) 我使用 RegisterNibForCellReuse 注册我的手机。

2.) 而不是在构造函数中使用 this.DelayBind(() =>。我在 AwakeFromNib override:

中进行绑定
public override void AwakeFromNib()
{
    base.AwakeFromNib();

    var binding = this.CreateBindingSet<MyCell, MyCellViewModel>();
    binding.Bind(TextView).To(vm => vm.GetType().Name).WithConversion(new StringFormatConverter(), "Unknown cell type: {0}");
    binding.Apply();
}