-2

我有一个 ListView,它具有 Checked = true 和两个组(已选择和未选择)。在检查时我希望将项目移动到适当的组,但似乎移动组会导致 ItemChecked 事件再次触发。

private void Form1_Load(object sender, EventArgs e)
{
    listView1.ItemChecked += listView1_ItemChecked;
}

private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
    foreach (ListViewItem item in listView1.Items)
    {
        if (item.Checked && item.Group != listView1.Groups["grpSelected"])
        {
            Console.WriteLine("Checked = true [1] : " + item.Text);
            item.Group = listView1.Groups["grpSelected"];
            Console.WriteLine("Checked = true [2] : " + item.Text);
            break;
        }
        if (!item.Checked && item.Group != listView1.Groups["grpNotSelected"])
        {
            Console.WriteLine("Checked = false [1] : " + item.Text);
            item.Group = listView1.Groups["grpNotSelected"];
            Console.WriteLine("Checked = false [2] : " + item.Text);
            break;
        }
    }
}

输出中的结果来自 Checked --> !Checked

Checked = false [1] : test0
Checked = true [1] : test0
Checked = true [2] : test0
Checked = false [2] : test0

有没有更好的方法来获得这个功能?或者解决问题的方法?目前我需要双击才能获得想要的效果,但它非常难看!

编辑

这有效,但似乎也是错误的......

private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
    listView1.ItemChecked -= listView1_ItemChecked;
    foreach (ListViewItem item in listView1.Items)
    {
        if (item.Checked && item.Group != listView1.Groups["grpSelected"])
        {
            item.Group = listView1.Groups["grpSelected"];
            item.Checked = true;
            break;
        }
        if (!item.Checked && item.Group != listView1.Groups["grpNotSelected"])
        {
            item.Group = listView1.Groups["grpNotSelected"];
            item.Checked = false;
            break;
        }
    }
    listView1.ItemChecked += listView1_ItemChecked;
}
4

1 回答 1

0

尝试这个:

//Suppose the first Group is Checked, the second Group is Unchecked    
//ItemCheck event handler for your listView1
private void listView1_ItemCheck(object sender, ItemCheckEventArgs e){
   listView1.Items[e.Index].Group = listView1.Groups[e.NewValue == CheckState.Checked ? 0 : 1];
}
//you need to do this initially to group your items correctly
foreach (ListViewItem item in listView1.Items)
     item.Group = listView1.Groups[item.Checked ? 0 : 1];
于 2013-10-18T20:40:46.717 回答