从ViewModel将焦点设置为UWP中的文本框

时间:2017-01-31 09:34:29

标签: uwp template10

任何人都告诉我如何在UWP Mobile应用中将焦点从ViewModel设置为TextBox。我的Senario是

  1. 用户扫描条形码:手动输入
  2. 我的ViewNodel将TextBox.Visibility上的绑定从Collapsed更改为Visible
  3. 我想触发SetFocusTapped事件,因此标记位于TextBox内,并显示键盘。

1 个答案:

答案 0 :(得分:2)

虽然ViewModel并不适合这种情况,但从ViewModel设置焦点的最佳方法是为它创建一个依赖属性,然后绑定到它。

public static class FocusExtension
{
    public static bool GetIsFocused(Control obj)
    {
        return (bool)obj.GetValue(IsFocusedProperty);
    }

    public static void SetIsFocused(Control obj, bool value)
    {
        obj.SetValue(IsFocusedProperty, value);
    }

    public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached(
        "IsFocused", typeof(bool), typeof(FocusExtension),
        new PropertyMetadata(false, OnIsFocusedPropertyChanged));

    private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var control = (Control)d;

        if ((bool)e.NewValue != (bool)e.OldValue)
        {
            if ((bool)e.NewValue)
            {
                control.Focus(FocusState.Programmatic);
                control.LostFocus += Control_LostFocus;
            }
            else
            {
                control.GotFocus += Control_GotFocus;
            }
        }
    }

    private static void Control_GotFocus(object sender, RoutedEventArgs e)
    {
        var control = (Control)sender;
        control.SetValue(IsFocusedProperty, true);
        control.GotFocus -= Control_GotFocus;
    }

    private static void Control_LostFocus(object sender, RoutedEventArgs e)
    {
        var control = (Control)sender;
        control.SetValue(IsFocusedProperty, false);
        control.LostFocus -= Control_LostFocus;
    }
}

你可以像这样绑定它(建议使用双向绑定,因为焦点将被设置一次,因为失去焦点后属性不会被设置回false)

<TextBox extensions:FocusExtension.IsFocused="{Binding IsTextBoxFocused, Mode=TwoWay}"/>