我的UI表单加载时无法将键盘焦点设置在文本框控件上。我正在使用MVVM模式和我 尝试解决以下link,但这没有帮助。当表单加载时,有一个插入符号 在我的文本框中,但它没有闪烁,我不能在其中写文字。我使用时会发生同样的事情 FocusManager.focused元素在XAML中。我也尝试过使用Keyboard.Focus(MytextBox),但同样的事情发生了......请帮助任何人,我被困2天......
这是我创建依赖项属性IsFocused的类,并使用它在我的viewmodel中与isFocused属性绑定:
public static class Attached
{
public static DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(Attached), new UIPropertyMetadata(false, OnIsFocusedChanged));
public static bool GetIsFocused(DependencyObject dependencyObject)
{
return (bool)dependencyObject.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject dependencyObject, bool value)
{
dependencyObject.SetValue(IsFocusedProperty, value);
}
public static void OnIsFocusedChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
TextBox textBox = dependencyObject as TextBox;
bool newValue = (bool)dependencyPropertyChangedEventArgs.NewValue;
bool oldValue = (bool)dependencyPropertyChangedEventArgs.OldValue;
Keyboard.Focus(textBox);
if (newValue && !oldValue && !textBox.IsFocused) textBox.Focus();
}
}
这是我的XAML:
<TextBox a:Attached.IsFocused="{Binding IsFocused, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True}.../>"