簡體   English   中英

C#Winforms:在數據綁定組合框中添加“從列表中選擇...”占位符

[英]C# Winforms: Add an “Select from list…” placeholder to databound combobox

我有一個像這樣數據綁定的組合框:

comboBox.InvokeIfRequired(delegate
        {
            var data = db.GetData();
            comboBox.DisplayMember = "Value";
            comboBox.ValueMember = "ID";
            comboBox.DataSource = data;
        });

它工作正常,但它預先選擇了第一個數據綁定值。 我希望使用像“從列表中選擇項目......”這樣的占位符來預先選擇組合框。

這樣做的最佳方式/方法是什么?
a)添加數據變量空項
b)通過combobox變量屬性設置它? 如果是這樣,哪些?
c)其他

我在這里找到了解決方案

這個代碼是:

private const int EM_SETCUEBANNER = 0x1501;        

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);

    [DllImport("user32.dll")]
    private static extern bool GetComboBoxInfo(IntPtr hwnd, ref COMBOBOXINFO pcbi);
    [StructLayout(LayoutKind.Sequential)]

    private struct COMBOBOXINFO
    {
        public int cbSize;
        public RECT rcItem;
        public RECT rcButton;
        public UInt32 stateButton;
        public IntPtr hwndCombo;
        public IntPtr hwndItem;
        public IntPtr hwndList;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct RECT
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }

    public static void SetCueText(Control control, string text)
    {
        if (control is ComboBox)
        {
            COMBOBOXINFO info = GetComboBoxInfo(control);
            SendMessage(info.hwndItem, EM_SETCUEBANNER, 0, text);
        }
        else
        {
            SendMessage(control.Handle, EM_SETCUEBANNER, 0, text);
        }
    }

    private static COMBOBOXINFO GetComboBoxInfo(Control control)
    {
        COMBOBOXINFO info = new COMBOBOXINFO();
        //a combobox is made up of three controls, a button, a list and textbox;
        //we want the textbox
        info.cbSize = Marshal.SizeOf(info);
        GetComboBoxInfo(control.Handle, ref info);
        return info;
    }

然后你可以像這樣簡單地使用它:

SetCueText(comboBox, "text");

這也適用於文本框。

只需使用Text Property並在那里寫“從列表中選擇項目......”

暫無
暫無

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

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