【发布时间】:2019-12-18 18:50:34
【问题描述】:
我有问题!
我有一个列表视图,其中包含随机数量的项目(根据文档的页面)。但我需要选择重新排序这些页面(它们是列表视图项)。我做了一个在两个按钮(向上和向下)上使用的功能,但它没有重新排序。例如:我有两个项目(第 1 页和第 2 页),我想将第 2 页移动到位置 0,它移动但在列表视图中它仍然显示以前的顺序。在我用更多页面制作的其他示例中。 下面是代码和他的电话。
private void moveImgList(int direction)
{
if (list_image.SelectedItems == null) { return; }
ListViewItem item = list_image.SelectedItems[0];
int newIndex = item.Index + direction;
if (newIndex < 0 || newIndex >= list_image.Items.Count) { return; }
list_image.Items.Remove(item);
list_image.Items.Insert(newIndex, item);
}
方法调用
private void btnLeft_Click(object sender, EventArgs e)
{
this.moveImgList(-1);
}
private void btnRight_Click(object sender, EventArgs e)
{
this.moveImgList(1);
}
应用程序 Windows 窗体 .NET 框架
原来是这样!
private void moveItem(int direction)
{
if (listView1.SelectedItems.Count == 0) { return; }
ListViewItem item = listView1.SelectedItems[0];
int newIndex = item.Index + direction;
if (newIndex < 0 || newIndex >= listView1.Items.Count) { return; }
var currentView = listView1.View;
listView1.BeginUpdate();
listView1.View = View.Details;
listView1.Items.Remove(item);
listView1.Items.Insert(newIndex, item);
listView1.EnsureVisible(newIndex);
listView1.View = currentView;
listView1.EndUpdate();
}
【问题讨论】:
-
您的代码按预期工作。在
BeginUpdate()EndUpdate()序列中执行索引更改只是消除了闪烁。删除Refresh(),不是必须的。 -
您可以在
moveImgList()调用之后的 ButtonsClick事件中添加list_image.Focus();(为了更好地查看索引更改:所选项目将保持可见选中状态)。 -
我输入了
list_image.Focus ();,但它也不起作用。我还是有同样的问题 -
这是your code at work,我刚刚添加了
list_image.EnsureVisible(newIndex);。它有什么问题? -
link 这是我在这里工作的代码
标签: c# winforms listview .net-4.0