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