如何使用MVVM将焦点设置为WPF控件?
我正在validation我的viewmodel中的用户输入并抛出validation消息,以防任何值的validation失败。
我只需要将焦点设置为validation失败的特定控件。
知道怎么做到这一点?
通常,当我们想要在遵守MVVM方法的同时使用UI事件时,我们会创建一个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(); }
此属性使用如下:
然后我们可以通过将IsFocused
属性更改为true
来从视图模型中聚焦TextBox
:
IsFocused = false; // You may need to set it to false first if it is already true IsFocused = true;