Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Focus to a WPF Control using MVVM?

I am validating user input in my viewmodel and throwing validation message in case validation fails for any of values.

I just need to set the focus to the particular control for which validation has failed.

Any idea how to achieve this ?

like image 346
user2519971 Avatar asked Oct 29 '13 12:10

user2519971


1 Answers

Generally, when we want to use a UI event while adhering to the MVVM methodology, we create an Attached Property:

public static DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(TextBoxProperties), 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;
    if (newValue && !oldValue && !textBox.IsFocused) textBox.Focus();
}

This property is used like this:

<TextBox Attached:TextBoxProperties.IsFocused="{Binding IsFocused}" ... />

Then we can focus the TextBox from the view model by changing the IsFocused property to true:

IsFocused = false; // You may need to set it to false first if it is already true
IsFocused = true;
like image 75
Sheridan Avatar answered Sep 19 '22 00:09

Sheridan