How to dynamically change Validation.ErrorTemplate based on the ErrorContent in xaml
I am trying to implement what is described in this answer. I would like to have one template for validation warnings and one for errors. I thought I had it figured out by binding to Validation.ErrorTemplate
in a style trigger like this:
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="Validation.ErrorTemplate" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Converter={StaticResource ValidationTemplateConverter}, Path=(Validation.Errors)[0].ErrorContent}" ></Setter>
</Trigger>
</Style.Triggers>
</Style>
The converter simply takes a key from the ErrorContent and does a lookup in a ResourceDictionary
for the correct template. Unfortunately开发者_运维百科 this doesn't work because binding to Validation.ErrorTemplate
is not allowed -- ArgumentException
'ErrorTemplate' property cannot be data-bound.
Parameter name: dp
Anybody else try to implement something like this?
Couldn't you move this logic into a DataTemplateSelector
? I'm assuming you're binding Validation.Errors
to some sort of ItemsControl
-- that ItemsControl
can have a DataTemplateSelector
that displays the error content differently depending on if it is a warning or an error.
If you're only showing the first error then you could always have your template include a ContentControl
, DataBind the Content
to Validation.Errors[0]
and apply a ContentTemplateSelector
<Style TargetType="TextBox">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel>
<ItemsControl ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(Validation.Errors)"
ItemTemplateSelector="{StaticResource ErrorTemplateSelector}" />
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
精彩评论