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

前端 未结 7 1292
小蘑菇
小蘑菇 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条回答
  •  情深已故
    2020-11-29 04:05

    This is the same as Ian Oakes' solution, but I made a couple minor changes.

    1. The button type can be more general, namely ButtonBase, to handle more cases, such as ToggleButton.
    2. The target type can also be more general, namely UIElement. Technically, this could be IInputElement, I suppose.
    3. Made the event handler static so that it won't generate a runtime closure every time this is used.
    4. [edit: 2019] Updated to use null-conditional and C#7 expression body syntax.

    Many thanks to Ian.


    public sealed class EventFocusAttachment
    {
        public static UIElement GetTarget(ButtonBase b) => (UIElement)b.GetValue(TargetProperty);
    
        public static void SetTarget(ButtonBase b, UIElement tgt) => b.SetValue(TargetProperty, tgt);
    
        public static readonly DependencyProperty TargetProperty = DependencyProperty.RegisterAttached(
                "Target",
                typeof(UIElement),
                typeof(EventFocusAttachment),
                new UIPropertyMetadata(null, (b, _) => (b as ButtonBase)?.AddHandler(
                    ButtonBase.ClickEvent,
                    new RoutedEventHandler((bb, __) => GetTarget((ButtonBase)bb)?.Focus()))));
    };
    

    Usage is basically the same as above:

    
    

    Note that the event can target/focus the originating button itself.

提交回复
热议问题