I want to add an exclamation mark Image to the left of the built-in TextBox
and make it visible whenever the TextBox
Validation.HasError
attached property is true, otherwise hide it.
How can I use ControlTemplate
to add the Image without having re-bind all the TextBox
properties?
<StackPanel>
<StackPanel.Resources>
<ControlTemplate x:Key="TextBoxWithIndicator" TargetType="{x:Type TextBox}">
<StackPanel Orientation="Horizontal">
<!-- Re-bind {Binding Path=Property}, including some that I may miss -->
<TextBox Text="{TemplateBinding Text}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/>
<Image Source="resources/exclaim.png" Visibility="{TemplateBinding Validation.HasError}"/>
</StackPanel>
</ControlTemplate>
</StackPanel.Resources>
<TextBox Template="{StaticResource TextBoxWithIndicator}" Width="120">Happy Go Lucky</TextBox>
</StackPanel>
Note The preceding block of code represents my futile effort in WPF so far. It is probably also wrong on several counts, e.g. probably need a ValueConverter
for Visibility <--> Validation.HasError
; Setting Width="120"
on TextBox seems to adjust the StackPanel width instead of TextBox width despite the TemplateBinding, etc.
I would suggest looking into Adorners. These are special FrameworkElements
that are rendered in a special Adorner Layer on top of visual elements, and are intended to provide visual cues to the user.
The above link provides a summary of Adorners
as well as an example of a Custom Adorner
.