我正在验证视图模型中的用户输入,并在任何值验证失败时抛出验证消息。
我只需要将焦点设置到验证失败的特定控件。
有什么方法可以实现这一点吗?
我正在验证视图模型中的用户输入,并在任何值验证失败时抛出验证消息。
我只需要将焦点设置到验证失败的特定控件。
有什么方法可以实现这一点吗?
通常,当我们想要在遵循MVVM方法论的同时使用UI事件时,我们会创建一个附加属性
:
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();
}
这个属性的使用方法如下:
<TextBox Attached:TextBoxProperties.IsFocused="{Binding IsFocused}" ... />
然后,我们可以通过将IsFocused
属性更改为true
,从视图模型中聚焦于 TextBox
:
IsFocused = false; // You may need to set it to false first if it is already true
IsFocused = true;
Attached
是该类的命名空间。这就是为什么可以像这样访问该属性:Attached:TextBoxProperties.IsFocused
。 - Sheridan