I am trying to add text validation for the required field using the ValidationRule class. I have the following class implementation
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); } }
Further in my XAML I have the following implementation:
<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>
and to display the error message, I have the following error pattern style in 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>
The code compiles and works fine. Even the validationRule method gets into the debugger. But the problem is that the error message is not displayed.
I attached the model using the following code:
ApplicationUsersUIContract ss = new ApplicationUsersUIContract(); this.DataContext = ss;
I am new to WPF concept. What am I missing here? Any help is appreciated.
wpf xaml
Tech jay
source share