gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:04:47 27 4
gpt4 key购买 nike

我在我的 View 模型中验证用户输入并抛出验证消息以防任何值验证失败。

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

知道如何实现吗?

最佳答案

通常,当我们想在遵循 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}" ... />

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

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

关于c# - 如何使用 MVVM 将焦点设置为 WPF 控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19657951/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com