2

如何将焦点设置在TextBox按下F3键时。

换句话说,请执行以下操作:

private void Window_PreviewKeyDown(object sender, KeyEventArgs )
{
       switch (e.Key)
       {
           case Key.F3:
               myTextBox1.Focus();
               break;
           case Key.F4:
               myTextBox2.Focus();
               break;
           default:
               break;
      }
}

注意:我想用 xaml 来做。

4

1 回答 1

6

您可以通过创建一个带有快捷键的附加属性然后在托管该控件的窗口上创建一个输入绑定来做到这一点。它是一个有点复杂的类,但非常易于使用。

首先在下面的项目中添加一个新类。

 public class TextBoxHelper : DependencyObject
    {
        public class MvvmCommand : DependencyObject, ICommand
        {
            readonly Action<object> _execute;
            readonly Func<object, bool> _canExecute;
            public event EventHandler CanExecuteChanged;
            public MvvmCommand(Action<object> execute, Func<object, bool> canExecute = null)
            {
                if (execute == null) throw new ArgumentNullException("command");
                _canExecute = canExecute == null ? parmeter => MvvmCommand.AlwaysCanExecute() : canExecute;
                _execute = execute;
            }
            public object Tag
            {
                get { return (object)GetValue(TagProperty); }
                set { SetValue(TagProperty, value); }
            }
            public static readonly DependencyProperty TagProperty = DependencyProperty.Register("Tag", typeof(object), typeof(MvvmCommand), new PropertyMetadata(null));
            static bool AlwaysCanExecute()
            {
                return true;
            }
            public void EvaluateCanExecute()
            {
                EventHandler temp = CanExecuteChanged;
                if (temp != null)
                    temp(this, EventArgs.Empty);
            }
            public virtual void Execute(object parameter)
            {
                _execute(parameter == null ? this : parameter);
            }
            public virtual bool CanExecute(object parameter)
            {
                return _canExecute == null ? true : _canExecute(parameter);
            }
        }

        public static Key GetFocusKey(DependencyObject obj)
        {
            return (Key)obj.GetValue(FocusKeyProperty);
        }

        public static void SetFocusKey(DependencyObject obj, Key value)
        {
            obj.SetValue(FocusKeyProperty, value);
        }

        public static readonly DependencyProperty FocusKeyProperty =
            DependencyProperty.RegisterAttached("FocusKey", typeof(Key), typeof(TextBoxHelper), new PropertyMetadata(Key.None, new PropertyChangedCallback((s, e) =>
                {
                    UIElement targetElement = s as UIElement;
                    if (targetElement != null)
                    {
                        MvvmCommand command = new MvvmCommand(parameter => TextBoxHelper.FocusCommand(parameter))
                            {
                                Tag = targetElement, 
                            };
                        InputGesture inputg = new KeyGesture((Key)e.NewValue);
                        (Window.GetWindow(targetElement)).InputBindings.Add(new InputBinding(command, inputg));
                    }
                })));

        public static void FocusCommand(object parameter)
        {
            MvvmCommand targetCommand = parameter as MvvmCommand;
            if (targetCommand != null)
            {
                UIElement targetElement = targetCommand.Tag as UIElement;
                if (targetElement != null)
                {
                    targetElement.Focus();
                }
            }
        }
    }

现在在 XAML 中设置焦点键所需要做的就是指定 FocusKey 属性,下面的示例有 2 个文本框,一个在按下 F1 时获得焦点,另一个在按下 F7 时获得焦点。

<Window x:Class="WpfApplication5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication5"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Title="MainWindow" Height="131" Width="460">

    <Grid Margin="10">
        <TextBox Margin="0,0,0,60" local:TextBoxHelper.FocusKey="F1" />
        <TextBox Margin="0,35,0,0" local:TextBoxHelper.FocusKey="F7" />
    </Grid>
</Window>
于 2012-12-10T10:20:15.997 回答