Search code examples
c#wpfxamlmvvm

Focus on textBox on the page load with MVVM


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

Solution

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

    MyTextBox.Focus();