#919 – Changing the Border of a TextBox
October 2, 2013 6 Comments
You can change the border displayed around a TextBox using the BorderBrush and BorderThickness properties.
In the example below, we use a trigger to change the border of the TextBox that has focus.
<Window.Resources> <Style TargetType="{x:Type TextBox}"> <Setter Property="Template"> <Setter.Value> <!-- Modify default template, to change triggers --> <ControlTemplate TargetType="{x:Type TextBoxBase}"> <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> <ScrollViewer x:Name="PART_ContentHost" Focusable="False" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Opacity" TargetName="border" Value="0.56"/> </Trigger> <!-- Original triggers --> <!--<Trigger Property="IsMouseOver" Value="True"> <Setter Property="BorderBrush" TargetName="border" Value="#FF7EB4EA"/> </Trigger> <Trigger Property="IsKeyboardFocused" Value="True"> <Setter Property="BorderBrush" TargetName="border" Value="#FF569DE5"/> </Trigger>--> <!-- MY trigger --> <Trigger Property="IsFocused" Value="True"> <Setter Property="BorderBrush" Value="Green"/> <Setter Property="BorderThickness" Value="2"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid Margin="5"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Label Content="Your hobo name:"/> <TextBox Grid.Column="1" Height="25" Margin="5"/> <Label Grid.Row="1" Content="Favorite cheese:" /> <TextBox Grid.Row="1" Grid.Column="1" Height="25" Margin="5"/> </Grid>
Actually, there is a bug with BorderBrush. It doesn’t change it’s color with the Trigger IsMouseOver.
Actually, there’s a bug preventing the BorderBrush from changing!
Tiago, this isn’t a bug. There is a trigger in the default template for the TextBox that overrides the value that you try to set in a regular property trigger in a style. I’ve updated the post to show how to override the control template.
The only way to override this is creating a new ControlTemplate. If you just put a ….. The BorderBrush won’t change, but BorderThickness and everything you set will.
I’ve seen some people saying that you can override by setting the value of BorderThickness different than “1”, but I could not reproduce it!
BTW: I check both your blogs daily. Nice job.
Sorry about both double posts.
But here’s an example of the behavior I was talking about:
FontFamily will change but not BorderBrush!
Sorry: http://pastebin.com/5BBZRqtD