如何使用 MVVM 将焦点设置为 WPF 控件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19657951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set Focus to a WPF Control using MVVM?
提问by user2519971
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 ?
知道如何实现这一目标吗?
回答by Sheridan
Generally, when we want to use a UI event while adhering to the MVVM methodology, we create an Attached Property:
通常,当我们想要在坚持 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();
}
This property is used like this:
这个属性是这样使用的:
<TextBox Attached:TextBoxProperties.IsFocused="{Binding IsFocused}" ... />
Then we can focus the TextBoxfrom the view model by changing the IsFocusedproperty to true:
然后我们可以TextBox通过将IsFocused属性更改为来关注视图模型true:
IsFocused = false; // You may need to set it to false first if it is already true
IsFocused = true;

