我在WPF应用程序中已验证密码。我正在使用IDataErrorInfo接口。带有验证模板的xml代码:
<UserControl.Resources>
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<Border BorderBrush="Red" BorderThickness="1" Margin="0,-30,20,0" Height="23" Width="250" DockPanel.Dock="Bottom" >
</Border>
<TextBlock DockPanel.Dock="Right" Foreground="Red" FontSize="25" FontWeight="Bold"
ToolTip="{Binding ElementName=Adorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">!</TextBlock>
<AdornedElementPlaceholder Name="Adorner" VerticalAlignment="Center" >
</AdornedElementPlaceholder>
</DockPanel>
</ControlTemplate>
<DataTemplate x:Key="ErrorViewerItemTemplate" DataType="string" >
<StackPanel Orientation="Horizontal">
<Ellipse Fill="Red" Width="5" Height="5" VerticalAlignment="Center"
HorizontalAlignment="Center" Margin="5,0,0,0" />
<TextBlock Text="{Binding}" FontSize="11" FontStyle="Italic" Foreground="red" Padding="2" Margin="5,0,0,0" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid x:Name="mainGrid">
<Label x:Name="passLabel" Content="Password" FontWeight="Bold" />
<Border BorderBrush="Green" BorderThickness="1" HorizontalAlignment="Left" Margin="135,40,0,0" Height="23">
<PasswordBox local:PasswordBoxAssistant.BindPassword="True"
x:Name="passwordBox" Validation.ErrorTemplate="{StaticResource validationTemplate}" HorizontalAlignment="Left" Height="23" Margin="0,0,0,0">
<local:PasswordBoxAssistant.BoundPassword>
<Binding Path="Password" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" >
<Binding.ValidationRules>
<NotifyDataErrorValidationRule />
</Binding.ValidationRules>
</Binding>
</local:PasswordBoxAssistant.BoundPassword>
</PasswordBox>
</Border>
</Grid>
密码的实现IDataErrorInfo接口:
class ConnectionSettings : INotifyPropertyChanged, IDataErrorInfo
{
private string _password;
public string Password
{
get
{
return _password;
}
set
{
_password = value;
OnPropertyChanged(nameof(Password));
}
}
... // realization INotifyPropertyChanged interface
public string this[string columnName]
{
get
{
string errorMessage = String.Empty;
switch (columnName)
{
...
case "Password":
if (string.IsNullOrEmpty(Password))
{
errorMessage = "Validation error: Enter the data in the field";
}
else if (!RegexPasswordValid(Password))
{
errorMessage = "Validation error: The password does not match the template or short password (minimum 8 characters)";
}
break;
...
}
return errorMessage;
}
}
private bool RegexPasswordValid(string value)
{
string pattern = @"^(\w{8,})$";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
bool isRegexValid = (regex.IsMatch(value)) ? true : false;
return isRegexValid;
}
public string Error
{
get { throw new NotImplementedException(); }
}
对于绑定密码,我使用PasswordBoxAssistant class。
我尝试将Mode="TwoWay"
设置为绑定和ValidatesOnDataErrors=True,
ValidatesOnExceptions=True
,但这并不能解决我的问题。
所以,请至少以某种方式帮助我修复它。)