WPF - Set Focus when a button is clicked - No Code Behind

前端 未结 7 1291
小蘑菇
小蘑菇 2020-11-29 03:53

Is there a way to set Focus from one control to another using WPF Triggers?

Like the following example:



        
7条回答
  •  -上瘾入骨i
    2020-11-29 04:10

    You could also use a WPF Behavior...

        public class FocusElementAfterClickBehavior : Behavior
    {
        private ButtonBase _AssociatedButton;
    
        protected override void OnAttached()
        {
            _AssociatedButton = AssociatedObject;
    
            _AssociatedButton.Click += AssociatedButtonClick;
        }
    
        protected override void OnDetaching()
        {
            _AssociatedButton.Click -= AssociatedButtonClick;
        }
    
        void AssociatedButtonClick(object sender, RoutedEventArgs e)
        {
            Keyboard.Focus(FocusElement);
        }
    
        public Control FocusElement
        {
            get { return (Control)GetValue(FocusElementProperty); }
            set { SetValue(FocusElementProperty, value); }
        }
    
        // Using a DependencyProperty as the backing store for FocusElement.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FocusElementProperty =
            DependencyProperty.Register("FocusElement", typeof(Control), typeof(FocusElementAfterClickBehavior), new UIPropertyMetadata());
    }
    

    Here is the XAML to use the behavior.

    Include namespaces:

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
    xmlns:local="clr-namespace:WpfApplication1"
    

    Attach WPF Behavior to button and bind element you want to set focus to:

    
    
    

    So this way you have no code behind and it is reusable on any control that inherits from ButtonBase.

    Hope this helps someone.

提交回复
热议问题