尝试验证用户名文本框字段时遇到问题。当我失去焦点时我除了验证器显示错误。
我在其中创建了formptment ValidationRule
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (this.username == null)
return new ValidationResult(false, "value cannot be empty.");
else
{
if (this.username.ToString().Length > 3)
return new ValidationResult
(false, "Name cannot be more than 3 characters long.");
}
return ValidationResult.ValidResult;
}
在xaml中我设置了控制模板
<ControlTemplate x:Key="validationErrorTemplate">
<DockPanel>
<StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
<Grid Width="12" Height="12">
<Ellipse Width="12" Height="12"
Fill="Red" HorizontalAlignment="Center"
VerticalAlignment="Center"
></Ellipse>
<TextBlock Foreground="White" FontWeight="Heavy"
FontSize="8" HorizontalAlignment="Center"
VerticalAlignment="Center" TextAlignment="Center"
ToolTip="{Binding ElementName=ErrorAdorner,
Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
>X</TextBlock>
</Grid>
<TextBlock Foreground="Red" FontWeight="12" Margin="2,0,0,0"
Text="{Binding ElementName=ErrorAdorner,
Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
></TextBlock>
</StackPanel>
<AdornedElementPlaceholder
x:Name="ErrorAdorner" ></AdornedElementPlaceholder>
</DockPanel>
</ControlTemplate>
对于我的textBox用户名,我声明
<TextBox x:Name="usernameTextBox" Validation.ErrorTemplate="{StaticResource validationErrorTemplate}" HorizontalAlignment="Left" Height="23" Margin="115,31,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="277" PreviewKeyDown="OnUsernameTextBoxKeyDown">
<TextBox.Text>
<Binding Path="Username" Mode="TwoWay" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<local:UsernameValidator></local:UsernameValidator>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox
UsernameValidator类是我的验证类。
程序成功完成错误和更改。
我遵循本教程:http://www.codeproject.com/Tips/690130/Simple-Validation-in-WPF
答案 0 :(得分:0)
WPF副设计默默地无法进行绑定操作(如同在正常操作期间没有向用户显示任何内容)。
但是,当您在调试器下运行WPF程序(例如Visual Studio中的Run + Debug按钮)时,您将看到“输出”窗口中显示的绑定错误。