Привязка ячейки к словарю - PullRequest
0 голосов
/ 20 мая 2018

У меня возникла странная проблема, которую я не знаю, как исправить.В моем iOS-проекте у меня есть TableViewCell и TableSource. Предполагается, что мой TableSource заполняет каждую ячейку такой информацией, как:

private Dictionary<string, List<Item>> savedItemList;

    protected override UITableViewCell GetOrCreateCellFor(UITableView tableView, NSIndexPath indexPath, object item)
    {
        //var foo = savedItemList.ElementAt(indexPath.Section).Value;
        //var Item = foo[indexPath.Row];

        NSString cellIdentifier;
        cellIdentifier = CellsIdentifier.Key;

        var cell = (MyTableViewCell)TableView.DequeueReusableCell(cellIdentifier, indexPath);

        return cell;
    }

public override nint NumberOfSections(UITableView tableView)
{
    return savedItemList.Count;
}


public override string TitleForHeader(UITableView tableView, nint section)
{

    return savedItemList.Keys.ElementAt((int)section);
}

Пока что заголовки и все работают без проблем, но я не уверенкак на самом деле связать данные изнутри ячейки.В настоящее время у меня есть

public partial class MyTableViewCell : MvxTableViewCell
{
    public static readonly NSString Key = new NSString("MyTableViewCell");
    public static readonly UINib Nib;

    protected MyTableViewCell(IntPtr handle) : base(handle)
    {
        SelectionStyle = UITableViewCellSelectionStyle.None;

        this.DelayBind(() =>
        {


            var set = this.CreateBindingSet<MyTableViewCell, Item>();
            set.Bind(LBL_NAME)
               .To(item => item.Name)
               .Apply();
        });
        // Note: this .ctor should not contain any initialization logic.
    }
}

Но когда я загружаю это представление, я получаю:

MvxBind:Warning:  8.03 Unable to bind: source property source not found Property:Name on KeyValuePair`2
MvxBind:Warning:  8.03 Unable to bind: source property source not found Property:Name on KeyValuePair`2

И у меня остается текст метки по умолчанию.Как мне настроить привязку для чтения данных из Dict?

1 Ответ

0 голосов
/ 21 мая 2018

Как вы настроили свою ViewModel?Вы должны привязать ваш TableView.Source ItemsSource к вашей ViewModel, а затем установить свои данные там:

Вот мой код привязки в View :

var source = new TableSource(TableView);
TableView.Source = source;
TableView.RowHeight = 120f;
TableView.ReloadData();

var set = this.CreateBindingSet<FirstView, FirstViewModel>();

set.Bind(source).For(s => s.ItemsSource).To(vm => vm.ItemsGroup);

set.Apply();

ViewModel может выглядеть следующим образом :

public class FirstViewModel : MvxViewModel
{

    public FirstViewModel()
    {
        // Emulate three groups here.
        ItemsGroup = new List<SessionGroup>();
        for (int i=0; i<3; i++)
        {
            var list = new List<Item>();
            for (int j=0; j<10; j++)
            {
                list.Add(new Item { Name = "Section:" + i + "Item" + j });
            }
            ItemsGroup.Add(new SessionGroup("section" + i, list));
        }
    }


    private List<SessionGroup> _ItemsGroup;
    public List<SessionGroup> ItemsGroup
    {
        get
        {
            return _ItemsGroup;
        }
        set
        {
            _ItemsGroup = value;
            RaisePropertyChanged(() => ItemsGroup);
        }
    }
}

public class Item
{
    public string Name { set; get; }
}

public class SessionGroup : List<Item>
{
    public string Key { get; set; }

    public SessionGroup(string key, List<Item> items) : base(items)
    {
        Key = key;
    }
}

После этой привязки мы можем представить TableView.вот мой MvxTableViewSource:

public class TableSource : MvxTableViewSource
{
    private static readonly NSString CellIdentifier = new NSString("MyTableViewCell");

    public TableSource(UITableView tableView)
            : base(tableView)
    {
        tableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
        tableView.RegisterNibForCellReuse(UINib.FromName("MyTableViewCell", NSBundle.MainBundle),
                                            CellIdentifier);
    }


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


    protected override object GetItemAt(NSIndexPath indexPath)
    {
        var _sessionGroup = ItemsSource.ElementAt(indexPath.Section) as SessionGroup;
        if (_sessionGroup == null)
            return null;

        return _sessionGroup[indexPath.Row];
    }

    public override nint NumberOfSections(UITableView tableView)
    {
        return ItemsSource.Count();
    }

    public override nint RowsInSection(UITableView tableview, nint section)
    {
        var group = ItemsSource.ElementAt((int)section) as SessionGroup;
        return group.Count();
    }

    public override string TitleForHeader(UITableView tableView, nint section)
    {
        var group = ItemsSource.ElementAt((int)section) as SessionGroup;
        return string.Format($"Header for section {group.Key}");
    }
}

Обновление:

Если вы хотите связать свой ItemsSource с Dictionary<>, просто изменитеGetItemAt() событие:

protected override object GetItemAt(NSIndexPath indexPath)
{
    return savedItemList.Values.ToList()[indexPath.Section][indexPath.Row];
}

public override nint NumberOfSections(UITableView tableView)
{
    if (ItemsSource != null)
    {
        savedItemList = (Dictionary<string, List<Item>>)ItemsSource;
        return savedItemList.Count();
    }           
    return 0;
}

public override nint RowsInSection(UITableView tableview, nint section)
{
    if (ItemsSource != null)
    {
        savedItemList = (Dictionary<string, List<Item>>)ItemsSource;
        return savedItemList.Values.ToList()[(int)section].Count;
    }
    return 0;
}

В нем указывается Модель, которая будет использоваться в классе ячеек.

Я тоже обновляю демо 1033 *, пожалуйста, проверьте его.

...