开发者

Setting focus to a control in WPF using MVVM

开发者 https://www.devze.com 2023-02-04 15:01 出处:网络
I want keyboard focus 开发者_开发百科to be set to a TextBox when I click a Button on my view.I don\'t want to use any codebehind, so wondered if anyone had written an attached property or similar solu

I want keyboard focus 开发者_开发百科to be set to a TextBox when I click a Button on my view. I don't want to use any codebehind, so wondered if anyone had written an attached property or similar solution?


Try this out:

public static class FocusBehavior
{
    public static readonly DependencyProperty ClickKeyboardFocusTargetProperty =
        DependencyProperty.RegisterAttached("ClickKeyboardFocusTarget", typeof(IInputElement), typeof(FocusBehavior),
        new PropertyMetadata(OnClickKeyboardFocusTargetChanged));

    public static IInputElement GetClickKeyboardFocusTarget(DependencyObject obj)
    {
        return (IInputElement)obj.GetValue(ClickKeyboardFocusTargetProperty);
    }

    public static void SetClickKeyboardFocusTarget(DependencyObject obj, IInputElement value)
    {
        obj.SetValue(ClickKeyboardFocusTargetProperty, value);
    }

    private static void OnClickKeyboardFocusTargetChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var button = sender as ButtonBase;
        if (button == null)
            return;

        if (e.OldValue == null && e.NewValue != null)
            button.Click += OnButtonClick;
        else if (e.OldValue != null && e.NewValue == null)
            button.Click -= OnButtonClick;
    }

    private static void OnButtonClick(object sender, RoutedEventArgs e)
    {
        var target = GetKeyboardClickFocusTarget((ButtonBase)sender);

        Keyboard.Focus(target);
    }
}

Then to use it,

<TextBox x:Name="TargetTextBox"/>
<Button b:FocusBehavior.ClickKeyboardFocusTarget="{Binding ElementName=TargetTextBox}"/>
0

精彩评论

暂无评论...
验证码 换一张
取 消