防止在C#中刷新列表视图时项目失去焦点 [英] prevent item losing focus when refreshing list view in c#

查看:115
本文介绍了防止在C#中刷新列表视图时项目失去焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有列表视图和一些列"ID",产品名称"和供应商".我可以添加,编辑或删除这些项目,并在与项目列表视图保持一致"后刷新类似的内容.

I have list view and some columns "ID", "product name" and "Vendor". I can add, edit or delete those items and after "messing up" with items list view is refreshed something like this.

listView.Items.Clear();
foreach (var item in result)
{
    ListViewItem lv = new ListViewItem(item.ID.ToString());
    lv.SubItems.Add(item.Name.ToString());
    lv.SubItems.Add(item.Vendor.ToString());
    listView.Items.Add(lv);
}

因此,此方法除每次刷新项目的列表焦点都丢失外均能正常工作,这是合乎逻辑的,因为我从列表中删除了所有项目,然后再次填充了它.所以我的问题是,当我编辑某些项目时,我该如何集中精力于已编辑和新添加的项目上,我希望listview不会滚动到顶部而是停留在该已编辑项目所在的位置.我尝试使用FindItemWithText方法,然后将listview的重点项目设置为找到的项目,但是它没有用.这类问题有解决方案吗?

so this method works fine except every time i refresh list focus of item is lost, which is logical because i deleted all items from list and filled it again. So my problem is how can i keep focus on edited and newly added items, primary when i edit some items i would like listview not to scroll to the top but to stay on place where that edited item was. I tried with method FindItemWithText and than setting focused items of listview to item that is found but it didn't work. Is there ant solution to this kind of problem?

推荐答案

将重点项目的索引保存到变量中:

Save focused item's index to the variable:

int oldFocusedIndex = listView.SelectedItems[0].Index;

之后,您可以恢复执行焦点:

Later then you can restore focus executing:

listView.Items[oldFocusedIndex].Selected = true;

由于 ListView 的滚动条将保留在 Clear()方法之后的顶部,因此您也可以使该项目对用户可见:

You can also make the item visible to the user due to the ListView's scroll bar will remain at the top after the Clear() method:

listView.Items[oldFocusedIndex].EnsureVisible();

这篇关于防止在C#中刷新列表视图时项目失去焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆