簡體   English   中英

CheckedListBox控件 - 僅在單擊實際復選框時選中復選框

[英]CheckedListBox Control - Only checking the checkbox when the actual checkbox is clicked

我在我正在使用的小應用程序中使用CheckedListBox控件。 這是一個很好的控制,但有一件事困擾我; 我無法設置屬性,以便在我實際選中復選框時僅檢查項目。 克服這個問題的最佳方法是什么? 我一直在考慮從復選框的左側獲取鼠標點擊的位置。 這部分工作,但如果我點擊一個空的空格,左邊足夠靠近,仍然會檢查當前所選項目。 關於這個的任何想法?

我知道這個帖子有點舊,但我不認為提供另一個解決方案是個問題:

private void checkedListBox1_MouseClick(object sender, MouseEventArgs e)
{
    if ((e.Button == MouseButtons.Left) & (e.X > 13))
    {
        this.checkedListBox1.SetItemChecked(this.checkedListBox1.SelectedIndex, !this.checkedListBox1.GetItemChecked(this.checkedListBox1.SelectedIndex));
    }
}

CheckOnClick = True的值)。

你可以在矩形中使用那個東西,但為什么要使它變得更加復雜。

嗯,這很難看,但你可以通過掛鈎CheckedListBox.MouseDownCheckedListBox.ItemCheck來計算項目矩形的鼠標點擊坐標,如下所示

/// <summary>
/// In order to control itemcheck changes (blinds double clicking, among other things)
/// </summary>
bool AuthorizeCheck { get; set; }

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
    if(!AuthorizeCheck)
        e.NewValue = e.CurrentValue; //check state change was not through authorized actions
}

private void checkedListBox1_MouseDown(object sender, MouseEventArgs e)
{
    Point loc = this.checkedListBox1.PointToClient(Cursor.Position);
    for (int i = 0; i < this.checkedListBox1.Items.Count; i++)
    {
        Rectangle rec = this.checkedListBox1.GetItemRectangle(i);
        rec.Width = 16; //checkbox itself has a default width of about 16 pixels

        if (rec.Contains(loc))
        {
            AuthorizeCheck = true;
            bool newValue = !this.checkedListBox1.GetItemChecked(i);
            this.checkedListBox1.SetItemChecked(i, newValue);//check 
            AuthorizeCheck = false;

            return;
        }
    }
}

另一種解決方案是簡單地使用Treeview。
將CheckBoxes設置為true,將ShowLines設置為false,將ShowPlusMinus設置為false,並且您與CheckedListBox基本相同。 僅在單擊實際CheckBox時才檢查項目。

CheckedListBox更加簡單,但TreeView提供了許多可能更適合您的程序的選項。

默認情況下,CheckedListBox中復選框的文本是在復選框輸入后放置HTML標簽,並將標簽的“for”屬性設置為復選框的ID。

當標簽表示它是“for”的元素時,單擊該標簽會告訴瀏覽器關注該元素,這就是您所看到的。

兩個選項是使用單獨的CheckBox控件和文本(不像CheckBox的Text屬性那樣呈現自己的列表,因為它與CheckBoxList做同樣的事情)如果列表是靜態的,或者如果列表是列表,則使用類似Repeater的內容動態。

試試這個。 將iLastIndexClicked聲明為表單級int變量。

private void chklst_MouseClick(object sender, MouseEventArgs e)
{
  Point p = chklst.PointToClient(MousePosition);
  int i = chklst.IndexFromPoint(p);
  if (p.X > 15) { return; } // Body click. 
  if (chklst.CheckedIndices.Contains(i)){ return; } // If already has focus click anywhere works right.
 if (iLastIndexClicked == i) { return; } // native code will check/uncheck
  chklst.SetItemChecked(i, true);  
  iLastIndexClicked = i;
}

只需檢查用戶是否點擊了選中列表的最左側15個像素(復選框區域),除了重新檢查當前選定的項目外,它始終有效。 存儲最后一個索引並退出而不進行更改會使本機代碼正確處理,嘗試將其設置為檢查,在這種情況下將其打開,並在“ItemCheck”代碼運行時關閉。

暫無
暫無

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

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