Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation, Show Data Error on multiple controls

Tags:

c#

validation

wpf

I need to validate a field bound to a TextBox , it's DataContext implements IDataErrorInfo

  <TextBox x:Name="txt" Text="{Binding PatientID, ValidatesOnDataErrors=True}" />

I need the Error to be shown on the TextBox and for the sake of simplicity 2 more textblocks in my form :

  <TextBox x:Name="txt" Text="{Binding Name, ValidatesOnDataErrors=True}" />
  <TextBlock Text="TXT 1" Validation.ValidationAdornerSiteFor="{Binding ElementName=txt}" />
  <TextBlock Text="TXT 2" Validation.ValidationAdornerSiteFor="{Binding ElementName=txt}" />

The problem here is that using ValidationAdornerSiteFor does not leave the validation on the TextBox mark on the TextBox it is applied solely on the UIElement using Validation.ValidationAdornerSiteFor secondly using Validation.ValidationAdornerSiteFor leaves only the last UIElement which used it marked with the validation error (TXT 2)

What mechanism can i use to show a Validation error that was raised on one field on 3 different controls including the one actually bound to the field (i.e. the TextBox) ,

by showing the Validation error i mean the red border (or any Validation Template) on the control.

like image 538
eran otzap Avatar asked Dec 31 '25 03:12

eran otzap


1 Answers

The simple way (However, not generic) will be to create a behaviour which adds an handler to OnDataError.

The behavior will contains 5 DP's: 3 x FrameWorkElement (For the textboxes) 1 bool which binds to the ViewModel HasError property (New property) 1 string which binds to the ViewModel ErrorDescription property (New property)

Now, You can create a DataTemplate which presents the TextBoxes with a red border and a tooltip whenever the HasError property changed to True.

Again, This is a simple non generic way for doing so.

like image 56
Moran Moshe Avatar answered Jan 02 '26 15:01

Moran Moshe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!