WPF Validation ErrorTemplate for custom TextBox

Including this question -

When attaching a validation error pattern to my custom text field, for example:

<local:CustomTextBox CustomText="{Binding ViewModelProperty}" Validation.ErrorTemplate="{StaticResource errorTemplate}"/> <ControlTemplate x:Key="errorTemplate"> <DockPanel> <Border BorderBrush="Red" BorderThickness="1"> <AdornedElementPlaceholder x:Name="controlWithError"/> </Border> <TextBlock Foreground="Red" FontSize="20" FontFamily="Segoe UI" Margin="3,0,0,0" MouseDown="Exclamation_MouseDown" Tag="{Binding AdornedElement.(Validation.Errors)[0].ErrorContent, ElementName=controlWithError}">!</TextBlock> </DockPanel> </ControlTemplate> 

If a validation error occurs in the ViewModelProperty, my application throws an exception -

 Key cannot be null. Parameter name: key 

I am not sure why this is happening. Is there something that needs to be done to assign a new error pattern to a custom control?

UPDATE:

I found out that the problem is related to the Tag property in the error pattern. If I remove the tag, it will work fine.

thanks

+6
source share
1 answer

Ok, so I was able to fix this problem by removing the AdornedElement keyword and changing the error pattern as follows:

 <local:CustomTextBox CustomText="{Binding ViewModelProperty}"> <Validation.ErrorTemplate> <ControlTemplate> <DockPanel> <Border BorderBrush="Red" BorderThickness="1"> <AdornedElementPlaceholder x:Name="controlWithError"/> </Border> <TextBlock Foreground="Red" FontSize="20" FontFamily="Segoe UI" Margin="3,0,0,0" MouseDown="Exclamation_MouseDown">!</TextBlock> </DockPanel> </ControlTemplate> </Validation.ErrorTemplate> <local:CustomTextBox.Style> <Style TargetType="{x:Type local:CustomTextBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/> <Setter Property="Tag" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </Style.Triggers> </Style> </local:CustomTextBox.Style> </local:CustomTextBox> 

I don’t understand why this happens differently when using the AdornedElement keyword, but it works fine when binding a Tag / Tooltip using RelativeSource. Although the problem is resolved, I would like to welcome any ideas as to why this happened.

thanks

+5
source

All Articles