簡體   English   中英

如何在獲勝形式的組合框中隱藏特定項目

[英]How to hide specific item from a combo box in win forms

如何從組合框中隱藏特定數量的項目。 下面的代碼將隱藏所有項目。 我找不到執行此操作的方法

string taskSelection = taskSelectionComboBox.Text;
string stateOfChild = stateOfChildComboBox.Text;
if (stateOfChild == "Awake")
{
    taskSelectionComboBox.Hide();
}

您需要存儲所需的項目,然后使用 remove 方法刪除它們。 您可以使用 add 使它們恢復原狀。

// keep the items in a list
List<string> list = new List<string>();
list.Add("Awake");
// remove them from combobox
comboBox1.Items.Remove("Awake");
// if you want to add them again.
comboBox1.Items.Add(list[0]);

我建議您查看DrawItemMeasureItem事件,並在其中創建邏輯。

// this is crucial as it gives the the measurement and drawing capabilities
// to the item itself instead of a parent ( ComboBox )
taskSelectionComboBox.DrawMode = DrawMode.OwnerDrawVariable;

taskSelectionComboBox.DrawItem +=TaskSelectionDrawItem;
taskSelectionComboBox.MeasureItem += TaskSelectionMeasureItem;

然后在TaskSelectionMeasureItem方法中將 height 設置為0

void TaskSelectionMeasureItem(object sender, MeasureItemEventArgs e)
{
    if(/* check if you want to draw item positioned on index e.Index */
        !CanDraw(e.Index) // or whatever else to determine
    )
        e.ItemHeight = 0;
}

之后,在繪圖方法 ( TaskSelectionDrawItem ) 中,您可以再次檢查它並繪制或不繪制該特定元素:

void TaskSelectionDrawItem(object sender, DrawItemEventArgs e)
{
    if(CanDraw(e.Index))
    {
        Brush foregroundBrush = Brushes.Black;
        e.DrawBackground();
        e.Graphics.DrawString(
            taskSelectionComboBox.Items[e.Index].ToString(),
            e.Font,
            foregroundBrush,
            e.Bounds,
            StringFormat.GenericDefault
        );
        e.DrawFocusRectangle();
    }
}

另一種方法是使用組合框的DataSource

var originalTasks = new List<string>
{
    "One",
    "Two",
    "Three",
    "Awake"
};

taskSelectionComboBox.DataSource = originalTasks;

然后,您將通過僅使用要顯示的項目重新分配DataSource來隱藏項目

taskSelectionComboBox.DataSource = originalTasks.Where(item => item != "Awake").ToList();

再次顯示所有項目

taskSelectionComboBox.DataSource = originalTasks;

這種方法適用於任何類型的物品。

基於我同事 Mateusz 的一個非常巧妙的方法:comboBox 中顯示的項目不必是文本字符串,而是任何具有 ToString() 方法輸出為項目的對象。 我們可以在這樣的對象中引入一個額外的 Hidden 屬性。 然后,在所描述的方法中,添加對該屬性的識別,並很自然地消除該項目的顯示。

替換

if (CanDraw(e.Index))
{
}

object item = combo.Items[e.Index];
var h = item.GetType().GetProperty("Hidden");
if (!(h == null) && h.GetValue(item).AsBool())
{

}

暫無
暫無

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

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