8

我正在我的视图模型中验证用户输入,并在验证任何值失败的情况下抛出验证消息。

我只需要将焦点设置在验证失败的特定控件上。

知道如何实现这一目标吗?

4

1 回答 1

13

通常,当我们想在遵循 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();
}

这个属性是这样使用的:

<TextBox Attached:TextBoxProperties.IsFocused="{Binding IsFocused}" ... />

然后我们可以通过将属性更改为来关注TextBox视图模型:IsFocusedtrue

IsFocused = false; // You may need to set it to false first if it is already true
IsFocused = true;
于 2013-10-29T12:25:31.940 回答