Set focus cursor to editable Combobox in WPF C #

I have an editable combobox in WPF and I want to set focus from C #,

I am using Combobox.Focus () but it only shows the selection, but I want an edit option where the user can start typing.

Update: computed by FIX

I ended up adding a "Loaded" Event to the Combobox and wrote the following code to get the focus and it worked Fine

    private void LocationComboBox_Loaded(object sender, RoutedEventArgs e)
    {
        ComboBox cmBox = (System.Windows.Controls.ComboBox)sender;
        var textBox = (cmBox.Template.FindName("PART_EditableTextBox",  
                       cmBox) as TextBox);
        if (textBox != null)
        {
            textBox.Focus();
            textBox.SelectionStart = textBox.Text.Length;
        }


    }

      

+3


source to share


3 answers


If you understand correctly, you have the following situation: you are setting focus on the ComboBox and watching the selected text inside the editable area, but you want it to be blank and only a blinking caret inside. If so, you can do it like this:



ComboBox.Focus();
ComboBox.Text = String.Empty;

      

+2


source


Try to create a focus extension like below and set the attached property to the textbox and bind it.

public static class FocusExtension
{
    public static bool GetIsFocused(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsFocusedProperty);
    }


    public static void SetIsFocused(DependencyObject obj, bool value)
    {
        obj.SetValue(IsFocusedProperty, value);
    }


    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached(
         "IsFocused", typeof(bool), typeof(FocusExtension),
         new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));


    private static void OnIsFocusedPropertyChanged(DependencyObject d,
        DependencyPropertyChangedEventArgs e)
    {
        var uie = (UIElement)d;
        if ((bool)e.NewValue)
        {
            OnLostFocus(uie, null);
            uie.Focus();
        }
    }

    private static void OnLostFocus(object sender, RoutedEventArgs e)
    {
        if (sender != null && sender is UIElement)
        {
            (sender as UIElement).SetValue(IsFocusedProperty, false);
        }
    }
}

      



XAML

 <TextBox Extension:FocusExtension.IsFocused="{Binding IsProviderSearchFocused}"/>

      

+1


source


Look at this. This might help you

Click Editable ComboBox WPF

0


source







All Articles