C# 窗体 : Add an "Select from list..." placeholder to databound combobox

标签 c# winforms data-binding combobox

我有一个像这样数据绑定(bind)的组合框:

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

它工作正常,但它预选了第一个数据绑定(bind)值。我希望使用一些占位符预选组合框,例如“从列表中选择项目...”

最好的方法是什么?
a) 添加到数据变量空项
b) 通过 combobox 变量属性设置?如果有,是哪些?
c) 其他

最佳答案

我找到了这个 here 的解决方案

代码是:

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");

这也适用于文本框。

关于C# 窗体 : Add an "Select from list..." placeholder to databound combobox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30622994/

相关文章:

c# - 更改 datagridview 列名称时无法搜索

c# - 我们可以在 C#.NET winform 中创建 4 个象限的 3D 图形吗?

.net - 图像 UriSource 和数据绑定(bind)

c# - 了解数据绑定(bind)如何在 UserControl 的 DependencyProperty 及其宿主应用程序的属性之间工作

c# - MVVM:强制组合框标签刷新

c# - 初始化语法

c# - 使用 WPF MVVM 预呈现/隐藏负载?

c# - 在 .NET Core 控制台应用程序 C# 中播放音频

winforms - 如何避免 Graphics.MeasureString() 中出现错误的零宽度连接器异常?

c# - 每个 Web 请求一个 DbContext ......为什么?