我正在尝试为WPF应用程序实现简单的文本框验证,但是遇到了一些问题。
我使用了这个指南:http://www.codeproject.com/Tips/690130/Simple-Validation-in-WPF
我的MainWindow.xaml中的文本框:
<TextBox x:Name="textbox1" HorizontalAlignment="Left" Height="23"
Margin="93,111,0,0" TextWrapping="Wrap" VerticalAlignment="Top"
Width="120" Style="{StaticResource textBoxInError}"
Validation.ErrorTemplate="{StaticResource validationErrorTemplate}">
<TextBox.Text>
<Binding Path="Name" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:NameValidator/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
MainWindow.xaml.cs中的NameValidator类:
public class NameValidator : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value == null)
return new ValidationResult(false, "value cannot be empty.");
else
{
if (value.ToString().Length > 3)
return new ValidationResult(false, "Name cannot be more than 3 characters long.");
}
return ValidationResult.ValidResult;
}
}
我的静态资源在App.xaml中:
<ControlTemplate x:Key="validationErrorTemplate">
<DockPanel>
<TextBlock Foreground="Red" DockPanel.Dock="Top">!</TextBlock>
<AdornedElementPlaceholder x:Name="ErrorAdorner"></AdornedElementPlaceholder>
</DockPanel>
</ControlTemplate>
<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
我可以成功运行应用程序,但是验证却从未被触发。
<Binding Path="Name" UpdateSourceTrigger="PropertyChanged">
。这应该在绑定标记中的Textbox.Text中,对吗? - user4681776