Set Cursor Focus into Editable Combobox in WPF C#

岁酱吖の 提交于 2019-12-01 06:41:05

Try Creating a Focus Extension like below, and set the attached property to the text box 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}"/>

If I understand you correctly, you have following situation: you set focus to ComboBox and observe selected text inside editable area, but you want it to be empty with only blinking caret inside. If so, you can do it this way:

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

Have a look at this. It might help you

Click WPF Editable ComboBox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!