如何填写C#comboBox中的空格作为用户的提示?

Jim*_*ell 2 c# combobox

当动态填充C#中的comboBox时,comboBox将显示为空白,直到用户单击它以查看下拉列表中的可用项目为止.理想情况下,我想使用此空白区域(在单击下拉列表之前)用于向用户提供有关他/她应该做什么的提示.例如,它可能会说"选择这样的......"有没有办法做到这一点?我尝试设置Text属性,但是没有做任何事情.我使用的是Microsoft Visual C#2008 Express Edition.谢谢.

Han*_*ant 8

它被称为"提示横幅".Windows窗体不支持它,但它可以用螺栓固定.在项目中添加一个新类并粘贴下面显示的代码.编译.将一个按钮和新控件从工具箱顶部拖放到表单上.将Cue属性设置为要显示的文本.需要Vista或Win7,只有在组合框没有焦点时才能看到提示.

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public class ComboBoxEx : ComboBox {
    private string mCue;
    public string Cue {
        get { return mCue; }
        set {
            mCue = value;
            updateCue();
        }
    }
    private void updateCue() {
        if (this.IsHandleCreated)
            SendMessageCue(this.Handle, CB_SETCUEBANNER, IntPtr.Zero, mCue ?? "");
    }
    protected override void OnHandleCreated(EventArgs e) {
        base.OnHandleCreated(e);
        updateCue();
    }
    // P/Invoke
    private const int CB_SETCUEBANNER = 0x1703;
    [DllImport("user32.dll", EntryPoint="SendMessageW", CharSet = CharSet.Auto)]
    private static extern IntPtr SendMessageCue(IntPtr hWnd, int msg, IntPtr wp, string lp);
}
Run Code Online (Sandbox Code Playgroud)


And*_*are 5

将"提示"项添加到组合框:

yourComboBox.Items.Insert(0, "Select one");
Run Code Online (Sandbox Code Playgroud)

然后将组合框的选定索引设置为0,如下所示:

yourComboBox.SelectedIndex = 0;
Run Code Online (Sandbox Code Playgroud)