一次只检查一个ListViewItem

Nic*_*ick 4 c# events listview compact-framework winforms

我正在使用Compact Framework开发智能设备项目.

我有ListView几个可检查的ListViewItems:属性CheckBoxes是真的.我需要每次只检查一个ListViewItem,所以我订阅了这个ItemCheck活动:

// I need to know the last item checked
private ListViewItem lastItemChecked;

private void listView_ItemCheck(object sender, ItemCheckEventArgs e)
{
    if (lastItemChecked != null && lastItemChecked.Checked)
    {
        /* I need to do the following to prevent infinite recursion:
        i.e. subscribe and then unsubscribe the ItemCheck event. */
        listView.ItemCheck -= listView_ItemCheck;
        lastItemChecked.Checked = false;
        listView.ItemCheck += listView_ItemCheck;
    }

    lastItemChecked = listView.Items[e.Index];
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来阻止无限递归,从而Stack Overflow

Nyu*_*uno 12

好吧,我认为比使用EventHandlers更好的方法是检查lastItemCheck是否是EventArgs中的当前项.像这样:

// I need to know the last item checked
private ListViewItem lastItemChecked;

private void listView_ItemCheck(object sender, ItemCheckEventArgs e)
{
    // if we have the lastItem set as checked, and it is different
    // item than the one that fired the event, uncheck it
    if (lastItemChecked != null && lastItemChecked.Checked
        && lastItemChecked != listView.Items[e.Index] )
    {
        // uncheck the last item and store the new one
        lastItemChecked.Checked = false;
    }

    // store current item
    lastItemChecked = listView.Items[e.Index];
}
Run Code Online (Sandbox Code Playgroud)

我认为你会同意,重新分配EventHandler比简单地检查存储对象的引用要差一些.

  • 如果listView.Items [e.Index] .Checked为true,您可以考虑存储lastItemChecked.然后条件会更简单:if(lastItemChecked!= null && lastItemChecked!= listView.Items [e.Index]){...} (3认同)