如何使用键绑定将文本框聚焦在xaml中?

时间:2012-12-10 05:47:49

标签: c# wpf textbox keypress

如何在按下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中完成。

1 个答案:

答案 0 :(得分: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属性,下面的一个例子有两个文本框,一个在按下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>