gpt4 book ai didi

c# - List.IndexOf 在 ListView 中删除项目后返回 -1

转载 作者:搜寻专家 更新时间:2023-11-01 09:26:41 26 4
gpt4 key购买 nike

好的,我有一个在 ListView 中查看的项目列表。我正在使用 ListView 中所选项目的索引。

“List.IndexOf(ListView.SelectedItem)”。从这里我将索引作为“id”存储到我以后用来检索信息等的数据库中。

当我从 ListView 中删除一个项目时,问题就来了。删除过程工作正常,但在我删除一个项目后,“List.IndexOf(ListView.SelectedItem)”返回 -1(直到我重新启动应用程序)而不是项目在 ListView 中放置位置的索引。为什么是这样?有没有办法解决?比如刷新整个 View 之类的?

    <mr:ListView x:Name="exampleListView" LongPressing="I_LongPressing">
<ListView.ItemTemplate>
<DataTemplate>
<ImageCell Text="{Binding mainSite}" TextColor="Black" Detail="{Binding link}" ImageSource="{Binding image}"></ImageCell>
</DataTemplate>
</ListView.ItemTemplate>
</mr:ListView>

Items = new List<ListViewItem>();
int itemValue = Items.IndexOf(exampleListView.SelectedItem); //this will return -1 if i delete an item from ListView aka the List (Items)

删除评论中建议的列表中项目的代码!

public async void I_LongPressing(object sender, MR.Gestures.LongPressEventArgs e)
{
var result = await DisplayAlert("Delete", "Are you sure you want to delete this object?", "Delete", "Cancel");
if (result == true)
{
ListViewItem k = (ListViewItem)exampleListView.SelectedItem;
dataBase.Query<ListViewItem>(string.Format("DELETE FROM [ListViewItem] WHERE [link] = '{0}'", k.link));

int itemValue = Items.IndexOf(exampleListView.SelectedItem);
dataBase.Query<ObjectAndNote>(string.Format("DELETE FROM [ObjectAndNote] WHERE item = '{0}'", itemValue));
Update();
}
}

public async void Update()
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var asyncCon = new SQLiteAsyncConnection(path + "/TestDB.dc3");

exampleListView.ItemsSource = new List<ListViewItem>();
List<ListViewItem> refreshedList = await asyncCon.QueryAsync<ListViewItem>("SELECT * FROM ListViewItem");
await asyncCon.QueryAsync<ObjectAndNote>(string.Format("UPDATE ObjectAndNote SET item = 'item--'"));
if (refreshedList.Count != 0)
{
exampleListView.ItemsSource = refreshedList;
}
}

亲切的问候

最佳答案

每次删除时,您都会执行此操作以刷新您的数据

List<ListViewItem> refreshedList = await asyncCon.QueryAsync<ListViewItem>("SELECT * FROM ListViewItem");

这会创建一个新列表,其中包含新项目,这些新项目是独特的对象,与之前存储在列表中的对象相同。

不要使用 IndexOf 来查找对象的特定实例,而是尝试通过 ID 或其他一些唯一元素查询列表以找到它在列表中的位置。或者,不刷新整个列表,只更新现有列表以删除已删除的项目。

关于c# - List.IndexOf 在 ListView 中删除项目后返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50092164/

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