I’m using a control template to show validation errors on each of my controls using the built-in WPF’s validation mechanism, and everything works fine. The controlTemplate looks like this:
<ControlTemplate x:Key="MyErrorTemplate" TargetType="{x:Type Control}">
<StackPanel Orientation="Horizontal">
<Border BorderBrush="Red" BorderThickness="2" CornerRadius="3">
<AdornedElementPlaceholder Name="MyAdorner" />
</Border>
<Image Name="imgError"
Source="/MyAssembly;component/Images/ValidationIcon.png"
ToolTip="{Binding ElementName=MyAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
</StackPanel>
</ControlTemplate>
I have read that the validation mechanism wraps the validated control up with the control template (the default one or a custom one like above) whenever the control gets an error.
“When the WPF validation system detects an invalid control it creates
and adorner that holds a control (…), inserts a control into it and sets that control
template to the content of the Validation.ErrorTemplate attached
property.It positions the adorner above the original control so that the
AdornedElementPlaceholder is exactly above the control and that let us
easily place the control template content relative to the original
control” (see more)
How can I perform this same behavior for another functionality? I mean use “MyErrorTemplate” without the WPF’s validation system, is it possible?
so if I understand you correctly you want to have the same validation adorning thing without WPF’s validation, right?
The approach then is actually to rebuild the components of WPF’s validation system:
create a Dependency Property
MyCustomErrorTemplateto hook up your template to the controlcreate a Dependency Property
HasCustomErrorto enable showing the errorwithin
MyCustomErrorTemplate_Changedhook up to theHasCustomError_Changedto enable showing/hiding of your adornercreate/copy the TemplatedAdorner Class that is then showing your Template
I recommend you use .NET Reflector or ILSpy to look at the following code to get some understanding of what’s going on. This isn’t actually very complex or hard to understand:
in PresentationFramework.dll:
System.Windows.Controls.Validation (especially the
private static void ShowValidationAdornerHelper(DependencyObject targetElement, DependencyObject adornerSite, bool show, bool tryAgain)MS.Internal.Controls.TemplatedAdorner (sadly this is internal, so you either have to copy it or use some Reflection on it)