WPF:Combobox的下拉列表高亮显示文本

Pan*_*nks 12 c# wpf combobox

当我输入组合框时,我自动打开启用下拉列表

searchComboBox.IsDropDownOpen = true;
Run Code Online (Sandbox Code Playgroud)

这里的问题是 - 文本突出显示,下一个按键会覆盖以前的文本.

如何在ComboBox DropDown打开时禁用文本突出显示?

小智 6

我遇到了同样的问题,就像一些刚接触WPF的用户一样,很难得到EinarGuðsteinsson给出的解决方案.所以为了支持他的答案,我在这里粘贴了让它发挥作用的步骤.(或者更准确地说我是如何使用它的).

首先创建一个继承自Combobox类的自定义组合框类.请参阅以下代码以获取完整实施 您可以更改OnDropSelectionChanged中的代码以满足您的个性化需求.

namespace MyCustomComboBoxApp {using System.Windows.Controls;

public class MyCustomComboBox : ComboBox
{
    private int caretPosition;

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        var element = GetTemplateChild("PART_EditableTextBox");
        if (element != null)
        {
            var textBox = (TextBox)element;
            textBox.SelectionChanged += OnDropSelectionChanged;
        }
    }

    private void OnDropSelectionChanged(object sender, System.Windows.RoutedEventArgs e)
    {
        TextBox txt = (TextBox)sender;

        if (base.IsDropDownOpen && txt.SelectionLength > 0)
        {
            txt.CaretIndex = caretPosition;
        }
        if (txt.SelectionLength == 0 && txt.CaretIndex != 0)
        {
            caretPosition = txt.CaretIndex;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

确保此自定义组合类存在于同一项目中.您可以使用以下代码在UI中引用此组合.

<Window x:Class="MyCustomComboBoxApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cc="clr-namespace:MyCustomComboBoxApp"
    Title="MainWindow" Height="350" Width="525" FocusManager.FocusedElement="{Binding ElementName=cb}">
<Grid>
    <StackPanel Orientation="Vertical">
        <cc:MyCustomComboBox x:Name="cb" IsEditable="True" Height="20" Margin="10" IsTextSearchEnabled="False" KeyUp="cb_KeyUp">
            <ComboBoxItem>Toyota</ComboBoxItem>
            <ComboBoxItem>Honda</ComboBoxItem>
            <ComboBoxItem>Suzuki</ComboBoxItem>
            <ComboBoxItem>Vauxhall</ComboBoxItem>
        </cc:MyCustomComboBox>
    </StackPanel>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

而已!如有任何问题,请询问!我会尽力帮忙.

感谢EinarGuðsteinsson的解决方案!


小智 5

迟到总比没有好,如果其他人遇到这个问题,他可能会使用这个.

如果你覆盖组合框,那么就有了这个.首先处理模板中使用的文本框并注册到selectionchanged事件.

public override void OnApplyTemplate()
{
  base.OnApplyTemplate();

  var element = GetTemplateChild("PART_EditableTextBox");
  if (element != null)
  {
    var textBox = (TextBox)element;
    textBox.SelectionChanged += OnDropSelectionChanged;
  }
}

private void OnDropSelectionChanged(object sender, RoutedEventArgs e)
{
    // Your code
}
Run Code Online (Sandbox Code Playgroud)

然后在事件处理程序中,您可以像您希望的那样再次设置选择.在我的情况下,我在代码中调用IsDropDownOpen.保存的选择然后将其放回事件处理程序中.丑陋但是做了伎俩.