我正在尝试使用"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);
}
}
Run Code Online (Sandbox Code Playgroud)
在我的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>
Run Code Online (Sandbox Code Playgroud)
并且为了显示错误消息,我在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>
Run Code Online (Sandbox Code Playgroud)
代码正在编译并运行正常.即使是validationRule方法也会受到调试器的攻击.但问题是没有显示错误消息.
我使用以下代码附加了Model:
ApplicationUsersUIContract ss = new ApplicationUsersUIContract();
this.DataContext = ss;
Run Code Online (Sandbox Code Playgroud)
我是WPF概念的新手.我在这里失踪了什么?任何帮助是极大的赞赏.
一切都很完美,除了即使在验证失败的情况下你也会传递isValid到-true
if (String.IsNullOrEmpty(str))
{
return new ValidationResult(true, this.ErrorMessage); <--- HERE
}
Run Code Online (Sandbox Code Playgroud)
它应该是假的 -
return new ValidationResult(false, this.ErrorMessage);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8036 次 |
| 最近记录: |