如何成功实现 WPF 文本框验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30762646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to successfully implement WPF textbox validation?
提问by Theodosius Von Richthofen
I'm trying to implement what should be simple textbox validation for a WPF application, but I'm having some problems.
我正在尝试为 WPF 应用程序实现应该是简单的文本框验证,但我遇到了一些问题。
I used this guide: http://www.codeproject.com/Tips/690130/Simple-Validation-in-WPF
我使用了本指南:http: //www.codeproject.com/Tips/690130/Simple-Validation-in-WPF
My textbox in MainWindow.xaml:
我在 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>
My NameValidator Class in MainWindow.xaml.cs:
我在 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;
}
}
My Static Resources in App.xaml:
我在 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>
I can run the application without any errors, but the validation is never triggered.
我可以在没有任何错误的情况下运行应用程序,但永远不会触发验证。
回答by Theodosius Von Richthofen
Using what you posted, it works fine for me, it produces the red "!" above the textbox. However, I DID remember to set my DataContext, ie.
使用您发布的内容,对我来说效果很好,它会产生红色的“!” 文本框上方。但是,我确实记得设置我的 DataContext,即。
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
Without this, it won't work.
没有这个,它就行不通。

