8

ビューのボタンをクリックすると、キーボード フォーカスが TextBox に設定されるようにします。コードビハインドを使用したくないので、誰かが添付プロパティまたは同様のソリューションを作成したかどうか疑問に思いましたか?

4

1 に答える 1

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}"/>
于 2011-01-14T20:23:49.757 に答える