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

9

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

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

有什么方法可以实现这一点吗?


概念:创建一个 AttachedBehavior 或自定义控件-添加新的依赖属性,当其设置为 true 时,您可以将焦点集中在该控件上,并将其重新设置为 false,以便下一次准备好再次设置为 true。 - bland
1
对于用户输入,控件已经拥有焦点,对吗?对于编程更改控件值,您如何确保只有一个控件无法通过验证?如果多个控件无法通过验证,哪个控件将被选择为焦点? - user2819245
这个问题的更好实现可以在这里找到:https://dev59.com/m3M_5IYBdhLWcg3wfTO7#7972361 - Coden
1个回答

13

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

2
@Sheridan:你是怎么引用 typeof(TextBoxProperties) 的?我的意思是需要访问哪个命名空间。 - user2519971
请阅读 MSDN 上的 附加属性概述 页面,以获取完整的解释...对于简短的解释,那就是我定义该属性的类。Attached 是该类的命名空间。这就是为什么可以像这样访问该属性:Attached:TextBoxProperties.IsFocused - Sheridan
1
不客气。如果这个答案为您提供了可接受的解决方案,请按照这个网站上的惯例,选择它作为被接受的答案,让其他用户知道。 - Sheridan
我收到一个错误提示,"TextBoxProperties在WPF项目中不受支持",你有什么想法我做错了什么吗? - Automate This
1
您需要通过定义XAML命名空间来导入附加属性(在此示例中,我使用的命名空间前缀是Attached,因此为Attached:TextBoxProperties)。 - Sheridan
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接