【问题标题】:Setting focus to a control in WPF using MVVM使用 MVVM 将焦点设置到 WPF 中的控件
【发布时间】:2011-06-09 07:21:49
【问题描述】:

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

【问题讨论】:

    标签: wpf mvvm textbox focus attached-properties


    【解决方案1】:

    试试这个:

    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}"/>
    

    【讨论】:

    • 谢谢,这给了我一个良好的开端!
    • 这个例子运行良好。但是,以下方法有微小的变化。您必须调用GetClickKeyboardFocusTarget 方法而不是GetKeyboardClickFocusTarget: private static void OnButtonClick(object sender, RoutedEventArgs e) { var target = GetKeyboardClickFocusTarget((ButtonBase)sender);键盘.焦点(目标); }
    猜你喜欢
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2020-10-14
    相关资源
    最近更新 更多