gpt4 book ai didi

c# - 如何将 XML 文件中的项目添加到已填充的 List<> 绑定(bind)到 ListBox

转载 作者:太空宇宙 更新时间:2023-11-03 22:01:00 26 4
gpt4 key购买 nike

嘿嘿 Stackoverflowers

我目前正忙于一个绑定(bind)了 List<> 的列表框。我通过对我们的 Web 服务器的 api 调用来填充此 List<>。现在,当我到达列表底部时,我会显示一个“加载更多”按钮,当我按下按钮时,我会开始另一个对我们的 api 的调用,但随后会调用 20 个新项目。现在是我的问题,我怎样才能将这 20 个新项目添加到我的列表 <> 中而不删除旧的 20 个。

这就是我现在填写列表<>的方式

eventList = (from item in events.Descendants("item")
select new Events
{
EventId = Convert.ToInt16(item.Element("eventid").Value),
EventName = item.Element("eventname").Value,
EventType = Convert.ToInt16(item.Element("type").Value)
}).ToList();

Dispatcher.BeginInvoke(new Action(
() =>
lbVanAlles.ItemsSource = eventList
));

但是如果我对我的 20 个新项目执行此操作,它们会覆盖我的旧项目。所以有人有任何线索吗?可能与 eventList.Add 有关,但后来出现错误,无法将其分配给“方法组”

最佳答案

不是每次都用 Linq 查询的结果覆盖 eventList,而是使用 List.AddRange将项目附加到现有列表的方法。

var temp = from item in events.Descendants("item")
select new Events
{
EventId = Convert.ToInt16(item.Element("eventid").Value),
EventName = item.Element("eventname").Value,
EventType = Convert.ToInt16(item.Element("type").Value)
};
eventList.AddRange( temp );

另外,不用每次都重新分配 lbVanAlles.ItemsSource 可以切换到使用 ObservableCollection而不是 List。这将在添加项目时通知 ListBox,它会自动更新。

关于c# - 如何将 XML 文件中的项目添加到已填充的 List<> 绑定(bind)到 ListBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10132926/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com