Show validation errors in WPF

WPF

Here is my approach: make the view model inerit from IErrorDataInfo, that creates the following two properties:



public string Error {get;set;} = null;

public string this[string columnName]
{
	get
    {
    	return OnValidate(columnName);
    }
}

The validation function might look as this one:


private string OnValidate(string columnName)
{
	string result = string.Empty;

    if (columnName == "SomeProperty")
    {
   		ValidationResult validationResult = new MyValidationRule().Validate(SomeProperty, null);
        if (validationResult.IsValid)
        {
        	Error = null;
        }
        else
        {
        	Error = "Error";
        	result = $"{validationResult.ErrorContent}";
        }
    }
            
   	return result;
}

The index operator, let you choose how or whether to validate a specific property

Now we need to add a TextBox to the XAML and tell it to do validation on input change:


<TextBox Text="{Binding SomeProperty, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" 
                Width="200" Height="25"
                VerticalContentAlignment="Center"
                >
</TextBox>

Add some style that shows the error as a tooltip:


 <Style TargetType="{x:Type TextBox}">
     <Style.Triggers>
         <Trigger Property="Validation.HasError" Value="true">
             <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)/ErrorContent}" />
         </Trigger>
     </Style.Triggers>
 </Style>

Post a Comment

Previous Post Next Post