Is there a way to set Focus
from one control to another using WPF Trigger
s?
Like the following example:
This is the same as Ian Oakes' solution, but I made a couple minor changes.
ButtonBase
, to handle more cases, such as ToggleButton
.UIElement
. Technically, this could be IInputElement
, I suppose.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.