我正在尝试使用“ValidationRule”类为必填字段的文本添加验证。我有以下类的实现
using System.Windows.Controls;
using System.Globalization;
public class RequiredField : ValidationRule
{
private String _errorMessage = String.Empty;
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; }
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
var str = value as string;
if (String.IsNullOrEmpty(str))
{
return new ValidationResult(true, this.ErrorMessage);
}
return new ValidationResult(true, null);
}
}
在我的 XAML 中,我有以下实现:
<TextBox Grid.Row="1" Grid.Column="3" Name="txtUserName" Height="23" VerticalAlignment="Top" Width="70" Grid.ColumnSpan="2" HorizontalAlignment="Left" MaxLength="50">
<TextBox.Text>
<Binding Path="Username" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<validators:RequiredField ErrorMessage="username is required." />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
为了显示错误消息,我在 app.xaml 中有以下错误模板样式
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Right"
Foreground="Orange"
Margin="5"
FontSize="12pt"
Text="{Binding ElementName=MyAdorner,
Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
</TextBlock>
<Border BorderBrush="Green" BorderThickness="3">
<AdornedElementPlaceholder Name="MyAdorner" />
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
代码正在编译并运行良好。甚至validationRule 方法也受到调试器的影响。但问题是没有显示错误消息。
我使用以下代码附加了模型:
ApplicationUsersUIContract ss = new ApplicationUsersUIContract();
this.DataContext = ss;
我是 WPF 概念的新手。我在这里想念什么?任何帮助是极大的赞赏。