TableView 绑定行选择和取消选择

时间:2021-06-19 10:01:30

标签: ios xamarin.ios mvvmcross

我有一个多选模式的 TableView。我想对单元格 Selected 属性进行两种方式绑定,以便能够在模型中设置它被选中,然后在重新打开视图时单元格也将被选中。

一切正常,但在我的模型中没有设置选择,重新打开后选择了任何单元格。如何做到这一点?或者也许这是处理单元格选择的更好方法?

我知道 source 中的 SelectionChangedCommand 仅在选择行时才起作用,但我还需要取消选择。我认为它可以通过覆盖源方法(下面的代码)来解决,但我认为这是解决方法,它必须是更好的解决方案。请帮忙,最好的方法是什么。

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        base.RowSelected(tableView, indexPath);

        var item = (Item) ItemsSource.ElementAt(indexPath.Row);

        item.Checked = true;
        tableView.CellAt(indexPath).Accessory = UITableViewCellAccessory.Checkmark;
    }

    public override void RowDeselected(UITableView tableView, NSIndexPath indexPath)
    {
        base.RowDeselected(tableView, indexPath);

        var item = (Item) ItemsSource.ElementAt(indexPath.Row);

        item.Checked = false;
        tableView.CellAt(indexPath).Accessory = UITableViewCellAccessory.None;
    }

我的模型

public class Item
{
    public Type Type { get; set; }
    public string Name { get; set; }
    public bool Checked { get; set; }
}

public enum Type
{
    Fruits,
    Vegetables
    //and more
}

单元格:

[Register("MyCustomCell")]
public class MyCustomCell : MvxTableViewCell
{
    public static readonly NSString Key = new NSString("MyCustomCell");
    public static readonly UINib Nib;

    static MyCustomCell()
    {
        Nib = UINib.FromName("MyCustomCell", NSBundle.MainBundle);
    }

    protected MyCustomCell(IntPtr handle) : base(handle)
    {

    }

    public override void AwakeFromNib()
    {
        base.AwakeFromNib();

        this.DelayBind(() =>
        {
            var set = this.CreateBindingSet< MyCustomCell, Item>();
            var converter = new BoolToCheckmarkAccessory();

            set.Bind(TextLabel).For(v => v.Text).To(vm => vm.Name);
            set.Bind(this).For(v => v.Selected).To(vm => vm.Checked);
            set.Bind(this).For(v => v.Accessory).To(vm => vm.Checked).WithConversion<BoolToCheckmarkAccessory>();

            set.Apply();
        });
    }
}

表源:

public abstract class MyTableSource<T> : MvxTableViewSource
{
    public MyTableSource(UITableView tableView) : base(tableView)
    {
    }

    protected override UITableViewCell GetOrCreateCellFor(UITableView tableView, NSIndexPath indexPath, object item)
    {
        return tableView.DequeueReusableCell(DocumentsAttributeViewCell.Key, indexPath);
    }

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        base.RowSelected(tableView, indexPath);

        tableView.CellAt(indexPath).Accessory = UITableViewCellAccessory.Checkmark;
    }

    public override void RowDeselected(UITableView tableView, NSIndexPath indexPath)
    {
        base.RowDeselected(tableView, indexPath);

        tableView.CellAt(indexPath).Accessory = UITableViewCellAccessory.None;
    }
}

0 个答案:

没有答案
相关问题