【发布时间】:2014-05-26 07:27:13
【问题描述】:
当我的 UI 表单加载时,我无法将键盘焦点设置在文本框控件上。我正在使用 MVVM 模式,当我在以下链接上尝试解决方案时,但这并没有帮助。当表单加载时,我的文本框中有一个插入符号,但它没有闪烁,我无法在其中写入文本。当我在 XAML 中使用 FocusManager.focused 元素时,也会发生同样的事情。我也试过 Keyboard.Focus(MytextBox) 但同样的事情发生了......请帮助任何人,我被困了 2 天......
这是我创建依赖属性 IsFocused 并将其用于在我的视图模型中与 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}.../>"
【问题讨论】:
-
这可能是因为它试图在渲染时设置焦点,在加载控件之前,你不能设置焦点。尝试使用
Dispatcher将焦点设置在稍后的DispatcherPriority,例如DispatcherPriority.Loaded,我认为它会起作用。