0
votes

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}.../>"
3
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

3 Answers

2
votes

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

MyTextBox.Focus();
1
votes

In the Window-Element you can write

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

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