How to add a focus to an editable ComboBox in WPF

后端 未结 4 2032
离开以前
离开以前 2021-01-12 08:17

I am using an editable ComboBox in wpf but when i try to set focus from C# code, it is only shows selection. but i want to go for edit option (cursor should display for user

4条回答
  •  鱼传尺愫
    2021-01-12 08:24

    You might try deriving from ComboBox and access the internal TextBox, like this:

    public class MyComboBox : ComboBox
    {
        TextBox _textBox;
    
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
    
            _textBox = Template.FindName("PART_EditableTextBox", this) as TextBox;
            if (_textBox != null)
            {
                _textBox.GotKeyboardFocus += _textBox_GotFocus;
                this.Unloaded += MyComboBox_Unloaded;
            }
        }
    
        void MyComboBox_Unloaded(object sender, System.Windows.RoutedEventArgs e)
        {
            _textBox.GotKeyboardFocus -= _textBox_GotFocus;
            this.Unloaded -= MyComboBox_Unloaded;
        }
    
        void _textBox_GotFocus(object sender, System.Windows.RoutedEventArgs e)
        {
            _textBox.Select(_textBox.Text.Length, 0); // set caret to end of text
        }
    
    }
    

    In your code you would use it like this:

    
        ...
            
                Alpha
                Beta
                Gamma
            
        ...
    
    

    This solution slightly dangerous, however, because in upcoming versions of WPF, Microsoft might decide also to add a GotKeyboardFocus event handler (or similar event handlers), which might get in conflict in with the event handler in MyComboBox.

提交回复
热议问题