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;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…