2012-09-06 53 views
2

我有一個ListView在第一列有複選框。當爲自定義排序編寫一些代碼時(當用戶點擊列標題時),我遇到了一些奇怪的行爲。當用戶單擊列標題時,我使用ColumnClickEventHandler將listView.Sorting設置爲SortOrder.Ascending(或SortOrder.Descending);當這行代碼被擊中時,它似乎會觸發ItemCheck事件處理程序。更改listView.sorting火災ItemCheckEventHandler

例如

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的事件處理程序被調用。

+0

listView或filesToSyncListView? –

+0

我從來沒有做過這樣的事情,但通過按標題,不列出選擇所有列,並通過觸發選定的事件? –

+0

@RaphaëlAlthaus道歉,我簡化了這個例子的代碼;他們應該有所有閱讀listView(現在固定在OP) – HaemEternal

回答

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

使用

listView_ColumnClick使用(同一個地方我的修改)布爾屬性(private bool disableItemCheck_)和

listView_ItemCheck 

if (disableItemCheck_) 
return; 
//ItemCheck logic 
+0

謝謝!這並沒有真正達到爲什麼它不工作的底部,但它確實完成了修復症狀。 – HaemEternal

+0

但是... listView.ItemCheck - = listView_ItemCheck需要去if else之外;因爲在else塊中進行排序的兩項更改也會啓動事件處理程序 – HaemEternal

+0

@HaemEternal,您是對的,已更正。 –