任何人都告诉我如何在UWP Mobile应用中将焦点从ViewModel
设置为TextBox
。我的Senario是
TextBox.Visibility
上的绑定从Collapsed
更改为Visible
SetFocus
或Tapped
事件,因此标记位于TextBox
内,并显示键盘。 答案 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}"/>