I am continuing my learning with a small project in C# WPF. My current situation is I want to make a border of a TextBox
change when an error occurs on a user input eg can not parse their input into a decimal number.
After some reading up I have used a control template, the XAML is below, but when I run the project the TextBox
using the control template (textBox1) does not show any text and I can not see what I have done wrong. Can any one help please?
Also I am triggering the change with a IsMouseOver
property just while I learn, but in my project I want to trigger off an error property so in my mind I would need to add to my TextBox
control a property IsError
as a bool and behind my code when I test the user input and it fails the Parse I would set the TextBox
property IsError
to true and that would trigger the ControlTemplate
change. However, can this be done or is there a more standed way to do this?
Thanks.
XAML of ControlTemplate
<Window x:Class="TestContentStyle.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="StyleTriggersSample" Height="100" Width="300">
<Window.Resources>
<!--A ControlTemplate for textbox including error-->
<ControlTemplate TargetType ="TextBox" x:Key="OnError">
<TextBox Name="TextBox"
FontSize="28"
HorizontalAlignment="Center"
VerticalAlignment="Center"
BorderBrush="Silver"
BorderThickness="1"
Height="50"
Width="120"/>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver"
Value="True">
<Setter TargetName="TextBox"
Property="BorderThickness"
Value="5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Window.Resources>
<Grid>
<TextBox Text="Tesing1" Margin="146,23,0,0" Name="textBox1" Template="{StaticResource OnError}" />
<TextBox Text="Testing2" Height="23" HorizontalAlignment="Left" Margin="12,23,0,0" Name="Test1" VerticalAlignment="Top" Width="120" />
</Grid>