如何使用MVVM将焦点设置为WPF控件?

use*_*971 8 c# wpf mvvm setfocus

我在我的viewmodel中验证用户输入并在任何值验证失败的情况下抛出验证消息.

我只需要将焦点设置为验证失败的特定控件.

知道怎么做到这一点?

She*_*dan 12

通常,当我们想要在遵守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();
}
Run Code Online (Sandbox Code Playgroud)

此属性使用如下:

<TextBox Attached:TextBoxProperties.IsFocused="{Binding IsFocused}" ... />
Run Code Online (Sandbox Code Playgroud)

然后我们可以TextBox通过将IsFocused属性更改为以下内容来关注视图模型true:

IsFocused = false; // You may need to set it to false first if it is already true
IsFocused = true;
Run Code Online (Sandbox Code Playgroud)

  • @Sheridan:你是怎么引用typeof(TextBoxProperties)的?我的意思是访问它所需的命名空间 (2认同)