专注于使用MVVM加载页面上的textBox

时间:2014-05-26 07:27:13

标签: c# wpf xaml mvvm

当我的UI表单加载时,我无法将键盘焦点设置在文本框控件上。我正在使用MVVM模式,当我在以下链接上尝试解决方案但这没有帮助。当表单加载时,我的文本框中有一个插入符但它没有闪烁,我无法在其中写入文本。当我在XAML中使用FocusManager.focused元素时,会发生同样的事情。我也尝试过使用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}.../>"

3 个答案:

答案 0 :(得分:1)

Window - 元素中你可以写

FocusManager.FocusedElement="{Binding ElementName=textBox}"

答案 1 :(得分:1)

为此你可以使用你的代码隐藏文件。在页面加载的事件中你应该做

MyTextBox.Focus();

答案 2 :(得分:0)

您可能会遇到加载时间问题,这意味着您设置了焦点,但之后它会被盗。您可以尝试使用调度程序推迟:

myView.Dispatcher.BeginInvoke(new Action(() =>
{
   textBox.Focus();
}), DispatcherPriority.ContextIdle);