Set focus on TextBox in WPF from view model

后端 未结 21 2524
爱一瞬间的悲伤
爱一瞬间的悲伤 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:39

    Anvakas brilliant code is for Windows Desktop applications. If you are like me and needed the same solution for Windows Store apps this code might be handy:

    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 PropertyMetadata(false, OnIsFocusedPropertyChanged));
    
    
        private static void OnIsFocusedPropertyChanged(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                var uie = d as Windows.UI.Xaml.Controls.Control;
    
                if( uie != null )
                {
                    uie.Focus(FocusState.Programmatic);
                }
            }
        }
    }
    

提交回复
热议问题