我尝试通过按钮向上/向下移动选定的ListView项目。 该项目被删除并插入相同的索引。但我想在索引+ 1(向下)或索引-1(向上)
添加它我有4件物品并试图向下移动第2项(在索引1处) 这是我的down_click程序的一个例子
child.properties
答案 0 :(得分:1)
您只需将列表视图的查看模式更改为列表:
listView1.View = View.List;
我希望它会有所帮助。
答案 1 :(得分:1)
实际上你的代码没有任何问题。问题出在ListView。
当您使用ListView并将View属性设置为LargIcon(视图属性的默认值)时,插入项目的SmallIcon或Tile View不会按预期工作,但在列表和详细信息视图中,它按预期工作。
要解决此问题,您可以执行以下任何操作:
解决方案1:(解决方法)
将ListView的View property设置为详细信息或列表。
解决方案2:(更好,更完整的解决方案)
要解决所有视图中的问题,请使用此UpdateLayout方法并在插入项目后调用它。
private void UpdateLayout()
{
if (this.listView1.View == View.LargeIcon ||
this.listView1.View == View.SmallIcon ||
this.listView1.View == View.Tile)
{
listView1.BeginUpdate();
//Force ListView to update its content and layout them as expected
listView1.Alignment = ListViewAlignment.Default;
listView1.Alignment = ListViewAlignment.Top;
listView1.EndUpdate();
}
}
所以UpButton和DownButton代码可能是这样的:
private void UpButton_Click(object sender, EventArgs e)
{
//If there is a selected item in ListView
if (this.listView1.SelectedIndices.Count >= 0)
{
//If selected item is not the first item in list
if (this.listView1.SelectedIndices[0] > 0)
{
var index = this.listView1.SelectedItems[0].Index;
var item = this.listView1.SelectedItems[0];
this.listView1.Items.RemoveAt(index);
this.listView1.Items.Insert(index - 1, item);
this.UpdateLayout();
}
}
}
private void DownButton_Click(object sender, EventArgs e)
{
//If there is a selected item in ListView
if (this.listView1.SelectedIndices.Count >= 0)
{
//If selected item is not the last item in list
if (this.listView1.SelectedIndices[0] < this.listView1.Items.Count - 1)
{
var index = this.listView1.SelectedItems[0].Index;
var item = this.listView1.SelectedItems[0];
this.listView1.Items.RemoveAt(index);
this.listView1.Items.Insert(index + 1, item);
this.UpdateLayout();
}
}
}
附加说明
要更好地了解ListView,请在设计器或代码中设置这些属性: