I’ve been trying everything to figure this issue out. 🙁
For a TextBox, I have a Validation.ErrorTemplate setup with an image on the right hand side of the textbox while it has a validation error.
This works great! But one thing I want to do is to resize or set the margin the textbox that has the error so it fits within the space the textbox has on the form. Currently, the image flows outside of the textboxes area.
What I really want is the textbox with error to take up the same space as textbox without.
Here is my XAML style:
<Style TargetType="{x:Type TextBox}">
<Style.Resources>
<my:TextBoxWidthTransformConverter x:Key="TextBoxWidthTransformConverter"/>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="Foreground" Value="Red"/>
<Setter Property="Margin" Value="{Binding Converter={StaticResource TextBoxWidthTransformConverter}, RelativeSource={RelativeSource Self}}"/>
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}"/>
</Trigger>
</Style.Triggers>
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<StackPanel
Margin="{TemplateBinding Margin}"
Orientation="Horizontal"
RenderOptions.BitmapScalingMode="NearestNeighbor"
>
<AdornedElementPlaceholder
Grid.Column="1"
Grid.Row="1"
Name="controlWithError"
/>
<Border Width="2"/>
<Image
ToolTip="{Binding ElementName=controlWithError, Path=AdornedElement.(Validation.Errors).CurrentItem.ErrorContent}"
Source="imagepath"
/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
I’m using a converter TextBoxWidthTransformConverter just to see if I can get something to happen, but before I was just using “0,0,20,0” in the Value, to no avail. The converter doesn’t fire, the Margin doesn’t change. I’ve used Snoop to see if I can see the property being touched or changed, but nothing happens.
Is Margin a property that can’t be changed by the Validation.HasError property?
Any insight would be wonderful!
Thanks!
Hope to help out anybody who may run up against this issue.
I’m still not sure why the Margin property is not changing during the Validation.HasError trigger, but I found a dirty work around.
The workaround hijacks the Width property binding with some events (TextChanged and Unloading for cleanup of the events) using an IValueConverter to set the Margin. I preserve the original Margin, in my case I’m only worried about the right margin, by utilizing the TextBoxes Tag property.
In your Validation.ErrorTemplate, apply the converter to Validation.HasError trigger: