更改listView.sorting会触发ItemCheckEventHandler

时间:2012-09-06 10:55:54

标签: c# .net

我有一个ListView,它在第一列上有复选框。在为自定义排序编写一些代码时(当用户单击列标题时),我遇到了一些奇怪的行为。

当用户单击列标题时,我使用ColumnClickEventHandler将listView.Sorting设置为SortOrder.Ascending(或SortOrder.Descending);当这行代码被命中时,它似乎触发了ItemCheck事件处理程序。

例如

listView.ItemCheck += new ItemCheckEventHandler(listView_ItemCheck);
listView.ColumnClick += new ColumnClickEventHandler(listView_ColumnClick);
...
...
void listView_ColumnClick(object sender, ColumnClickEventArgs e)
{
   // Determine whether the column is the same as the last column clicked.
   if (e.Column != sortColumn)
   {
      // Set the sort column to the new column.
      sortColumn = e.Column;
      // Set the sort order to ascending by default.
      listView.Sorting = SortOrder.Ascending;
   }
   else
   {
      // Determine what the last sort order was and change it.
      if (listView.Sorting == SortOrder.Ascending)
         listView.Sorting = SortOrder.Descending;
      else
         listView.Sorting = SortOrder.Ascending;
   }
}

行listView.Sorting = SortOrder.Descending之后;命中listView.ItemCheck的事件处理程序。

1 个答案:

答案 0 :(得分:3)

这可能是一个不好的伎俩,但你可以试试:

void listView_ColumnClick(object sender, ColumnClickEventArgs e)
{
   listView.ItemCheck -= listView_ItemCheck;
   // Determine whether the column is the same as the last column clicked.
   if (e.Column != sortColumn)
   {

      // Set the sort column to the new column.
      sortColumn = e.Column;
      // Set the sort order to ascending by default.
      listView.Sorting = SortOrder.Ascending;
   }
   else
   {
      // Determine what the last sort order was and change it.
      if (listView.Sorting == SortOrder.Ascending)
         listView.Sorting = SortOrder.Descending;
      else
         listView.Sorting = SortOrder.Ascending;

   } 
   listView.ItemCheck += listView_ItemCheck;
}

使用

中使用的布尔属性(private bool disableItemCheck_

listView_ColumnClick(与我的修改相同)和

listView_ItemCheck 

if (disableItemCheck_)
return;
//ItemCheck logic