【问题标题】:Index of Observablecollection and listview xamarin formsObservablecollection 和 listview xamarin 表单的索引
【发布时间】:2023-03-10 23:27:01
【问题描述】:

拼命地试图从一个单独的视图模型类中获取一个由可观察集合提供的列表视图的索引。

在我的主页中,它包含 listview xaml(称为“mainlist”)我有需要给我索引的 onitemselected 方法。

到目前为止,我已经尝试了所有方法。

这是唯一适用的代码,但它也给了我空引用异常:

            int index = (mainlist.ItemsSource as List<MainListItem>).IndexOf(e.SelectedItem as MainListItem);

说对象引用未设置为对象的实例。

我在这里缺少什么?

这是我创建 observablecollection 的 mainviewmodel.cs

private ObservableCollection<MainListItem> _list;

        public ObservableCollection<MainListItem> List
        {
            get { return _list; }
            set
            {
                _list = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(List)));
            }
        }

【问题讨论】:

  • 不要使用 ItemsSource,而是尝试使用对分配给 ItemsSource 的实际列表的引用
  • 谢谢杰森。我该怎么做?该列表是在另一个类中创建的。
  • @fredrik -- 完全不同。在标记重复之前请先检查!此外,这是在 c# 中
  • 空指针仍然是空指针 - 分解并调试它。

标签: listview xamarin.forms observablecollection indexof listviewitem


【解决方案1】:

最终我通过遍历整个列表并计算我自己的索引来解决它,如下所示:我知道必须有更好的方法,但由于我的列表相对较小,这对我很有帮助。

int index = 0;
int i = 1;

foreach (MainListItem itemtocheck in mainlist.ItemsSource as ObservableCollection<MainListItem>)
                {
                    if(itemtocheck == e.SelectedItem)
                    {
                        index = i;
                        Debug.WriteLine("Index is " + index);
                        break;
                    }
                    else
                    {

                        Debug.WriteLine("No match for index at " + i);
                        i++;
                    }

                }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 2018-08-14
    • 2016-10-03
    • 1970-01-01
    • 2018-03-11
    • 2018-10-16
    相关资源
    最近更新 更多