簡體   English   中英

如何獲取圖像ListView中所選項目的索引?

[英]How do I get the index of a selected item in an image ListView?

我正在用c#編寫WinForms程序來調整圖像大小。

我有一個ListView。 此ListView中的項目是來自ImageList的圖像。

當用戶將圖像拖放到窗體上時,將填充ImageList和ListView。

我還創建了兩個字符串數組,imageFilePaths []和imageFileNames [](這很容易解釋),它們與ImageList和ListView同時填充。

由於所有這四個對象都是通過dragDrop方法中的迭代填充的,因此ImageListListViewimageFilePaths []imageFileNames []的索引完美匹配。

我有一個用於ListView的事件偵聽器。 單擊ListView中的項目時,我從前面提到的數組中與ListView.SelectedItems索引匹配的索引位置獲取文件名和文件路徑。 這是代碼:

    private void imageListView_SelectedIndexChanged(object sender, EventArgs e)           
    {
        foreach (ListViewItem item in imageListView.SelectedItems)
        {
            int imgIndex = item.ImageIndex;
            if (imgIndex >= 0 && imgIndex < imageList1.Images.Count)
            {
                filenameTb.Text = imageFileNames[imgIndex];
                updateDimensions(imageFilePaths[imgIndex]);
            }
        }
    }

這可行,但不如我所願。 例如,如果我在ListView中有20張圖像,並嘗試通過按住Shift鍵並單擊來選擇區域,則將所有這些圖像突出顯示大約需要10-20秒。 這對我很重要,因為我還有一個“刪除所選內容”按鈕。 “取消選擇”項目所花費的時間一樣長。

我有95%的把握,這是因為此事件偵聽器正在遍歷每個單個項目,顯示每個選定項目的尺寸和文件名,直到到達最后一個為止,即使這不是必需的。

如何重新編寫此代碼,以便僅獲取所選項目的索引,或者如果選擇了多個,則獲取最后一項的索引?

謝謝

編輯:基於注釋,我查找了SelectedIndices屬性,並嘗試了以下操作:

    private void imageListView_SelectedIndexChanged(object sender, EventArgs e)
    {
        ListView.SelectedIndexCollection indexes = this.imageListView.SelectedIndices;
        foreach (int index in indexes)
        {
            filenameTb.Text = imageFileNames[index];
            updateDimensions(imageFilePaths[index]);
        }
    }

但是它仍然很慢...

 foreach (ListViewItem item in imageListView.SelectedItems.Select((value, i) => new { i, value })
{
    //your code
}

我在哪里索引並重視項目

而不是使用SelectedIndexChanged事件,請嘗試使用ItemSelectionChanged。 傳遞給該事件處理程序的事件將直接為您提供相關的項目。 無需重復。

        private void imageListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
    {
        e.Item ... <- this is your item
        e.ItemIndex ... <- this is your item's index
    }

不完全是我最初尋找的答案,但是我通過創建一個存儲圖像尺寸(x,y)的二維數組解決了選擇圖像緩慢的問題,而不是從圖像路徑中獲取所選圖像的尺寸,從將圖像放到表單上時初始化的數組中獲取它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM