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

时间:2013-10-29 12:14:30

标签: c# wpf mvvm setfocus

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

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

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

1 个答案:

答案 0 :(得分: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();
}

此属性的用法如下:

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

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

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