如何使用 MVVM 将焦点设置为 WPF 控件? [英] How to set Focus to a WPF Control using MVVM?

查看:32
本文介绍了如何使用 MVVM 将焦点设置为 WPF 控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am validating user input in my viewmodel and throwing validation message in case validation fails for any of values.

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

I just need to set the focus to the particular control for which validation has failed.

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

Any idea how to achieve this ?

推荐答案

一般来说,当我们想在坚持 MVVM 方法的同时使用 UI 事件时,我们会创建一个Attached Property:

Generally, when we want to use a UI event while adhering to the MVVM methodology, we create an 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();
}

这个属性是这样使用的:

This property is used like this:

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

然后我们可以通过将 IsFocused 属性更改为 true 来聚焦视图模型中的 TextBox:

Then we can focus the TextBox from the view model by changing the IsFocused property to true:

IsFocused = false; // You may need to set it to false first if it is already true
IsFocused = true;

这篇关于如何使用 MVVM 将焦点设置为 WPF 控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆