How to set Focus to a WPF Control using MVVM?

后端 未结 1 720
死守一世寂寞
死守一世寂寞 2020-12-06 02:29

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

相关标签:
1条回答
  • 2020-12-06 03:05

    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;
    
    0 讨论(0)
提交回复
热议问题