Set focus on TextBox in WPF from view model

后端 未结 21 2240
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 06:21

I have a TextBox and a Button in my view.

Now I am checking a condition upon button click and if the condition turns out to be false, displ

21条回答
  •  长情又很酷
    2020-11-22 06:32

    I have found solution by editing code as per following. There is no need to set Binding property first False then True.

    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)
        {
            if (d != null && d is Control)
            {
                var _Control = d as Control;
                if ((bool)e.NewValue)
                {
                    // To set false value to get focus on control. if we don't set value to False then we have to set all binding
                    //property to first False then True to set focus on control.
                    OnLostFocus(_Control, null);
                    _Control.Focus(); // Don't care about false values.
                }
            }
        }
    
        private static void OnLostFocus(object sender, RoutedEventArgs e)
        {
            if (sender != null && sender is Control)
            {
                (sender as Control).SetValue(IsFocusedProperty, false);
            }
        }
    }
    

提交回复
热议问题