0

I can't set keyboard focus on textbox control when my UI form loads. I am using MVVM pattern and when I tried solution on the following link but this didn't help. When the form loads there is a caret in my textbox but it's not flashing, and I can't write text in it. The same thing happens when I use FocusManager.focused element in XAML. I also tried with Keyboard.Focus(MytextBox) but the same thing happened... Please help anybody, I am stuck 2 days with this...

This is class where i made dependency property IsFocused and used it for binding with isFocused property in my viewmodel:

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();
}

}

This is my XAML:

<TextBox a:Attached.IsFocused="{Binding IsFocused, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True}.../>"
Enes H
  • 3
  • 3
  • possible duplicate of [Set focus on a textbox control in UserControl in wpf](http://stackoverflow.com/questions/19225443/set-focus-on-a-textbox-control-in-usercontrol-in-wpf) – franssu May 26 '14 at 07:44
  • Its probably because it's trying to set focus at render time, before the control is loaded, and you can't set focus then. Try using the `Dispatcher` to set the focus at a later `DispatcherPriority`, such as `DispatcherPriority.Loaded`, and I think it will work. – Rachel May 27 '14 at 18:31

3 Answers3

2

In the Window-Element you can write

FocusManager.FocusedElement="{Binding ElementName=textBox}"
Tomtom
  • 9,087
  • 7
  • 52
  • 95
2

For this u can use your code behind file. In the page loaded event you should do

MyTextBox.Focus();
JMan
  • 2,611
  • 3
  • 30
  • 51
0

You maybe get a problem with the loaded-timing, meaning you set focus but it gets stolen afterwards. You can try to defer that by using a dispatcher:

myView.Dispatcher.BeginInvoke(new Action(() =>
{
   textBox.Focus();
}), DispatcherPriority.ContextIdle);
Gope
  • 1,672
  • 1
  • 13
  • 19