Set Cursor Focus into Editable Combobox in WPF C#

后端 未结 3 1862
灰色年华
灰色年华 2021-01-14 02:48

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

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

3条回答
  •  离开以前
    2021-01-14 03:34

    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

     
    

提交回复
热议问题