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

查看:178
本文介绍了如何使用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事件,我们创建了一个附加属性

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();
}

这属性用于这样的:

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



然后我们可以将精力集中在文本框从鉴于通过改变 IsFocused 属性真实模型

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天全站免登陆