gpt4 book ai didi

c# - WPF:验证确认密码

转载 作者:行者123 更新时间:2023-11-30 12:16:07 26 4
gpt4 key购买 nike

我有 2 个密码框。我需要检查密码是否相等。我不想将此条件写入 [].xaml.cs 代码,但我想在密码不相等时将 PasswordBox 标记为红色。

我应该编写特殊的 ValidationRule、ViewModel 中的一些代码还是其他什么?谁能帮我?现在验证写在 [].xaml.cs 中,但我想避免它。

最佳答案

使用:

<PasswordBox Name="tbPassword" />
<PasswordBox Name="tbPasswordConf" />
<PasswordValidator
Box1="{Binding ElementName=tbPassword}"
Box2="{Binding ElementName=tbPasswordConf}" />

代码(此代码并未涵盖所有情况):

public class PasswordValidator : FrameworkElement
{
static IDictionary<PasswordBox, Brush> _passwordBoxes = new Dictionary<PasswordBox, Brush>();

public static readonly DependencyProperty Box1Property = DependencyProperty.Register("Box1", typeof(PasswordBox), typeof(PasswordValidator), new PropertyMetadata(Box1Changed));
public static readonly DependencyProperty Box2Property = DependencyProperty.Register("Box2", typeof(PasswordBox), typeof(PasswordValidator), new PropertyMetadata(Box2Changed));

public PasswordBox Box1
{
get { return (PasswordBox)GetValue(Box1Property); }
set { SetValue(Box1Property, value); }
}
public PasswordBox Box2
{
get { return (PasswordBox)GetValue(Box2Property); }
set { SetValue(Box2Property, value); }
}

private static void Box1Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
private static void Box2Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var pv = (PasswordValidator)d;
_passwordBoxes[pv.Box2] = pv.Box2.BorderBrush;
pv.Box2.LostFocus += (obj, evt) =>
{
if (pv.Box1.Password != pv.Box2.Password)
{
pv.Box2.BorderBrush = new SolidColorBrush(Colors.Red);
}
else
{
pv.Box2.BorderBrush = _passwordBoxes[pv.Box2];
}
};
}
}

此外,可以使用错误样式定义依赖属性并设置它而不是 BorderBrush。但我不知道如何在这种情况下使用标准的 ErrorTemplate。

关于c# - WPF:验证确认密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5960107/

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