繁体   English   中英

我该如何在Xaml中使用键绑定集中文本框?

[英]how can i focus textbox in xaml with keybinding?

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

换句话说,做下面的事情:

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来做。

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

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

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM