简体   繁体   English

C# ComboBox 禁用突出显示

[英]C# ComboBox disable highlighting

I have custom ComboBox, where DropDownStyle = ComboBoxStyle.DropDown;我有自定义 ComboBox,其中DropDownStyle = ComboBoxStyle.DropDown; .DropDown style is set because I want to set the Text property of the ComboBox to something outside the list of values.设置 .DropDown 样式是因为我想将 ComboBox 的 Text 属性设置为值列表之外的内容。 Everything works good, except that ComboBox is highlighting the text when it's left and when I click on the combobox editing is avaible.一切都很好,除了 ComboBox 在它离开时突出显示文本并且当我单击组合框时可以进行编辑。 How can I cope with this?我该如何应对? To illustrate:为了显示:

在此处输入图片说明

First Picture is where everything looks good, second is the highlight situation, third editing is on.第一张图片是一切看起来不错的地方,第二张是高光情况,第三张编辑打开。

Try un-selecting the text after the DropDown closes:在 DropDown 关闭尝试取消选择文本:

void comboBox1_DropDownClosed(object sender, EventArgs e) {
  this.BeginInvoke(new Action(() => { comboBox1.Select(0, 0); }));
}

Tricky problem to solve.棘手的问题要解决。 It seems to be from the Resize event.它似乎来自Resize事件。 There are a lot of solutions that do something similar to this, but none that I've seen worked for me until I tried this.有很多解决方案可以做类似的事情,但在我尝试之前,我见过的解决方案都没有对我有用。 (This is a solution that does not require inheritance from ComboBox ; inheriting is probably a much more straight forward solution, but requires you to always use your inherited class and never the actual ComboBox class.) (这是一个不需要从ComboBox继承的解决方案;继承可能是一个更直接的解决方案,但要求您始终使用继承的类,而不是实际的ComboBox类。)

comboBox.Resize += (s, e) => {
   if (!comboBox.IsHandleCreated)
      return;  // avoid possible exception

   comboBox.BeginInvoke(new Action(() => comboBox.SelectionLength = 0));
};

Set the selection length to zero to get rid of the highlight, but when?将选择长度设置为零以消除高光,但是什么时候? Other examples do it in other places, but the problem seems to be specifically caused by Resize , so doing it after Resize fixes it consistently, at least for me.其他示例在其他地方也这样做,但问题似乎是由Resize专门引起的,因此在Resize始终如一地修复它之后这样做,至少对我而言。 (Can still see it flicker when you resize the window though, but it always ends up ok.) (虽然当你调整窗口大小时仍然可以看到它闪烁,但它总是结束。)

BeginInvoke ensures that it happens sufficiently after Resize to work, and the check for IsHandleCreated prevents it from being called before the handle is created, in which case BeginInvoke would throw an exception. BeginInvoke确保它在Resize后充分发生才能工作,并且检查IsHandleCreated可防止在创建句柄之前调用它,在这种情况下, BeginInvoke将引发异常。

This slightly more complex version includes some checks to prevent a focused control from losing highlight, since it actually should have it.这个稍微复杂的版本包括一些检查,以防止焦点控件丢失高亮,因为它实际上应该拥有它。 It also doesn't fire if the parent doesn't exist yet, or if the parent does not have an active control yet, both signs that things are too early.如果父级还不存在,或者父级还没有活动控件,它也不会触发,这两种迹象都表明事情还为时过早。

comboBox.Resize += (s, e) => {
   if (!comboBox.IsHandleCreated)
      return;

   comboBox.BeginInvoke(new Action(() => {
      var parent = comboBox.FindForm();
      if (parent == null)
         return;

      if (parent.ActiveControl == null)
         return;

      if (parent.ActiveControl == comboBox)
         return;

      comboBox.SelectionLength = 0;
   }));
};

I tried to make a version that would 'preserve' the selection length rather than always set it to zero, but I couldn't get it to synchronize properly.我试图制作一个可以“保留”选择长度而不是始终将其设置为零的版本,但我无法使其正确同步。 Many Resize events can fire before the BeginInvoke delegates start to fire, so the preserved value will always be overwritten by the broken one.许多Resize事件可以在BeginInvoke委托开始触发之前触发,因此保留的值将始终被损坏的值覆盖。 I tried saving them all in a Queue or Stack , but in both cases, I was unable to reverse the ordering (not really sure why, since that makes no sense).我尝试将它们全部保存在QueueStack ,但在这两种情况下,我都无法颠倒顺序(不确定为什么,因为这没有意义)。

如果您指的是禁用突出显示和编辑,那么您可能需要考虑将DropdownStyle属性设置为DropdownList

yourComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

To solve the same I have tried almost EVERYTHING:为了解决同样的问题,我几乎尝试了所有方法:

  • setting the DropdownStyle property to DropdownListDropdownStyle属性设置为DropdownList
  • this.BeginInvoke(new Action(() => { comboBox1.Select(0, 0); }));
  • combobox1.SelectionLength = 0;
  • changing comboBox.TabIndex改变comboBox.TabIndex
  • Not tried SendKeys.Send("{ESC}");没试过SendKeys.Send("{ESC}"); because it is not a reliable solution因为它不是一个可靠的解决方案

Nothing helped.没有任何帮助。 The only stable and working solution was to move a focus on another Label control:唯一稳定且有效的解决方案是将焦点转移到另一个 Label 控件上:

    label.Focus();

You could also hide that label.您也可以隐藏该标签。

I know this post is old but recently I have the same problem with combobox.我知道这篇文章很旧,但最近我在组合框上遇到了同样的问题。

Situation : I have an editable combobox which propose complete words when user write some letters.情况:我有一个可编辑的组合框,当用户写一些字母时,它会建议完整的单词。

But when I want to type a letter, combobox auto highlight the text and the next letter auto replace the previous.但是当我想输入一个字母时,组合框会自动突出显示文本,下一个字母会自动替换上一个。

Solution : I use a textbox to avoid any highlight like that:解决方案:我使用文本框来避免任何类似的突出显示:

<ComboBox IsTextSearchEnabled="False" IsEditable="True" x:Name="CMB_ClientName"/>
<TextBox Text="{Binding ElementName=CMB_ClientName, Path=Text}" TextChanged="ComboBoxChange" x:Name="TXT_ClientName"/>

And I generate the textbox TextChanged event :我生成了文本框 TextChanged 事件:

private void ComboBoxChange(object sender, TextChangedEventArgs e)
    {
        //Clear ComboBox items
        CMB_ClientName.Items.Clear();
        //Auto Open DropDownList
        CMB_ClientName.IsDropDownOpen = true;

        //Get data from database (use entity framework 6.x)
        dbEntity.Client.Load();

        //Attribute Data to variable
        var clients = dbEntity.Client.Local;


        foreach (Client client in clients)
        {
            //If data begin with the texbox text, the data is add to the combobox items list.
            if (client.Nom.ToLower().StartsWith(TXT_NomClient.Text.ToLower()))
            {
                CMB_ClientName.Items.Add(client.Nom);
            }
        }
    }

I know this solution isn't realy beautifull, but it is for me the easiest solution to avoid highlight text and all the solutions in this post don't work for me.我知道这个解决方案不是很漂亮,但对我来说它是避免突出显示文本的最简单的解决方案,并且这篇文章中的所有解决方案对我都不起作用。

I hope this solution will be helpfull, thanks for reading.我希望这个解决方案会有所帮助,感谢阅读。

Math.数学。

Ps: My apologies, my English is not very good. Ps:抱歉,我的英文不是很好。 I hope you will understand me correctly.我希望你能正确理解我。

Nothing worked for me ( I want the form to load with no highlighting in any combobox) until I set the combobox property TabStop to false.在我将组合框属性 TabStop 设置为 false 之前,没有什么对我有用(我希望表单在任何组合框中都没有突出显示)。 This meant that one of my buttons took the tab highlight which I didn't like so I set them all to false for start up and adjusted them programatically as needed.这意味着我的一个按钮采用了我不喜欢的选项卡突出显示,因此我将它们全部设置为 false 以启动并根据需要以编程方式调整它们。

I know this is an old thread, but my solution is similar to that of the others, but relies on the Form.ResizeEnd event.我知道这是一个旧线程,但我的解决方案与其他解决方案类似,但依赖于 Form.ResizeEnd 事件。 In its event handler, I iterate through the ComboBoxes and set ComboBox.SelectionLength to 0.在其事件处理程序中,我遍历 ComboBoxes 并将 ComboBox.SelectionLength 设置为 0。

private void Form_ResizeEnd(object sender, EventArgs e)
{
    foreach(ComboBox comboBox in parentControl.Controls.OfType<ComboBox>
    {
        comboBox.SelectionLength = 0;
    }
}

This is what worked for me:这对我有用:

  1. Set DrawMode to OwnerDrawFixed将 DrawMode 设置为 OwnerDrawFixed

  2. Set cbxSubsystems.DrawItem event to the function below将 cbxSubsystems.DrawItem 事件设置为下面的函数

private void cbxSubsystems_DrawItem(object sender, DrawItemEventArgs e)
{
    Color BgClr;
    Color TxClr;

    if( (e.State & DrawItemState.ComboBoxEdit) == DrawItemState.ComboBoxEdit )
    {
        // Do not highlight main display
        BgClr = cbxSubsystems.BackColor;
        TxClr = cbxSubsystems.ForeColor;
    }
    else
    {
        BgClr = e.BackColor;
        TxClr = e.ForeColor;
    }

    e.Graphics.FillRectangle(new SolidBrush(BgClr), e.Bounds);

    TextRenderer.DrawText(e.Graphics, cbxSubsystems.Items[e.Index].ToString(), e.Font, e.Bounds,
        TxClr, BgClr, TextFormatFlags.Left | TextFormatFlags.VerticalCenter );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM