c# - 更改 listView.sorting 会触发 ItemCheckEventHandler

标签 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 的事件处理程序。

最佳答案

这可能是一个糟糕的技巧,但你可以尝试:

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;
}

使用 bool 属性(private bool disableItemCheck_)用于

listView_ColumnClick (与我的修改相同的位置)和

listView_ItemCheck 

if (disableItemCheck_)
return;
//ItemCheck logic

关于c# - 更改 listView.sorting 会触发 ItemCheckEventHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12298539/

相关文章:

c# - EF Core SetQueryFilter 在 OnModelCreating 中将 IsActive 反向为 IsDeleted

c# - 如何将鼠标从文本框中选择的文本添加到列表

.net - 如何通过查看项目属性来判断应用程序是 Winforms 应用程序还是 WPF 应用程序

c# - C#中所有的数组都实现了哪些接口(interface)?

c# - 将字节转换为图像时出现错误“参数无效”

c# - 运行一个异步任务至少需要多少个线程?

c# - 这里保存的分配是什么?

c# - 从 IEnumerable<IEnumerable<object>> linq 选择 IEnumerable<object>

c# - 如何使用只读用户访问 azure 应用程序服务的 log4net 日志文件夹

.net - 为什么在 dotnetnuke 中启用复合文件时 SVG 背景图像会中断?