消除Combobox显示下拉框后自动选中文本效果

public partial class MyCombobox : ComboBox
{
    public MyCombobox()
    {
        InitializeComponent();
    }

    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;
        }
    }
}

 

posted @ 2021-11-25 14:48  Kyle0418  阅读(239)  评论(0编辑  收藏  举报