使用MVVM将焦点设置为WPF中的控件

时间:2011-01-14 17:35:35

标签: wpf mvvm textbox focus attached-properties

我想在单击视图上的按钮时将键盘焦点设置为TextBox。我不想使用任何代码隐藏,所以想知道是否有人写了附加属性或类似的解决方案?

1 个答案:

答案 0 :(得分:5)

试试这个:

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);
    }
}

然后使用它,

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