簡體   English   中英

組合框中的.NET不可見項

[英].NET invisible items in combobox

我正在將字符串加載到組合框-

cboIndexLanguage.Items.Add("ThisLanguage")

我想使其中一些物品不可見。

我找到了解決方案。 可以通過綁定DataTable對象來完成:

            comboBox.DisplayMember = "VALUE";
            comboBox.ValueMember = "ID";

            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("VALUE");

            for (int i = 0; i < 5; i++)
            {
                DataRow row = dt.NewRow();
                row[0] = i;
                row[1] = "val"+i;
                dt.Rows.Add(row);
            }
            dt.AcceptChanges();

            comboBox.DataSource = dt;

然后只需找到要隱藏的項目並將其隱藏(通過將其設置為Deleted)即可:

dt.Select("ID = 2").First().Delete();

或全部隱藏:

dt.RejectChanges();

嘗試為每個項目發送CB_SETMINVISIBLE消息。

要么

根本就不要設置Text值!

稍后編輯:

int invItems = 5;
Message msg = new Message();
msg.Msg = CB_SETMINVISIBLE;
msg.LParam = 0;
msg.WParam = invItems;
msg.HWnd = combo.Handle;
MessageWindow.SendMessage(ref msg);

或調用此:

[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, uint Msg, long wParam, long lParam);

您可以使用其他列表來保留字符串並按組合框向用戶顯示所需的項目。為此,您可以定義Refresh_Combo_Method,清除組合框項目並將項目從字符串列表復制到組合,然后索引位於主列表中。

List<string> colorList = new List<string>();
colorList.Add ("Red");
colorList.Add ("Green");
colorList.Add ("Yellow");
colorList.Add ("Purple");
colorList.Add ("Orange");
...
colorList.Remove("Red");
colorList.Insert(2, "White");
colorList[colorList.IndexOf("Yellow")] = "Black";
colorList.Clear();


...

combobox.Items.Clear();

以線程安全的方式,您可以非常簡單地執行此操作(如果您只想玩顏色):

private delegate void SetBackColorDelegate(int index, Color color);
private void SetBackColor(int index, Color color)
    {
        if (cboIndexLanguage.InvokeRequired)
        {
            cboIndexLanguage.Invoke(new SetBackColorDelegate(SetBackColor), new object[] { index, color });
        }
        else
        {
            cboIndexLanguage.Items[index].BackColor = color;
        }
    }

換句話說,您可以從組合框中刪除項目,然后將其保存在某些數據結構f.ex中:

class ComboElement
{
     public String ComboElementText { get; set; }
     public int Index { get; set; }

    public ComboElement(String elementText, int index)
    {
       ComboElementText = elementText;
       Index = index;
    }
}

//* List of hidden elements.
List<ComboElement> hiddenElements = new List<ComboElement>();

然后您想再次顯示它,可以從這里獲取它,然后插入正確的位置(您知道索引)。

將它們添加到您的組合框

class MyCboItem
{
    public bool Visible { get; set; }
    public string Value { get; set; }
    public override string ToString()
    {
        if (Visible) return Value;
        return string.Empty;
    }
}

暫無
暫無

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

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