WPF and initial focus

后端 未结 12 2107
鱼传尺愫
鱼传尺愫 2020-11-29 15:59

It seems that when a WPF application starts, nothing has focus.

This is really weird. Every other framework I\'ve used does just what you\'d expect: puts initial foc

12条回答
  •  有刺的猬
    2020-11-29 16:32

    I also faced the same problem. I had three text boxes inside canvas container and wanted the first text box to be focused when the user control opens. WPF code followed MVVM pattern. I created a separate behavior class for focusing the element and binded it to my view like this.

    Canvas behavior code

    public  class CanvasLoadedBehavior : Behavior
    {
        private Canvas _canvas;
        protected override void OnAttached()
        {
            base.OnAttached();
            _canvas = AssociatedObject as Canvas;
            if (_canvas.Name == "ReturnRefundCanvas")
            {
    
                _canvas.Loaded += _canvas_Loaded;
            }
    
    
        }
    
        void _canvas_Loaded(object sender, RoutedEventArgs e)
        {
            FocusNavigationDirection focusDirection = FocusNavigationDirection.Next;
    
            // MoveFocus takes a TraveralReqest as its argument.
            TraversalRequest request = new TraversalRequest(focusDirection);
            UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
            if (elementWithFocus != null)
            {
                elementWithFocus.MoveFocus(request);
            }
    
        }
    
    }
    

    Code for view

    
                    
                        
                    
                    
                    
    

提交回复
热议问题