ivan ivan

ivan ivan

  • NA
  • 3
  • 4.7k

WPF Change Style of all TextBoxes in Grid

Dec 11 2013 12:02 AM
Dear All

Hi everyone,

I am using control template to change all the textboxes' style in specific Grid, all textboxes outside the Grid will have different style
I works fine with the following code, but I need one more enhancement

I would like to change a textbox's borderbrush to red when a button click, however, since I am set the color to Blue in style, the code textBox1.BorderBrush = Brushes.Red; is not working

How to modify the controlTemplate that normal style is Blue border and when a button is clicked, the code textBox1.BorderBrush = Brushes.Red; can change the border to Red?

Thanks
Ivan

Here are my codes:

XAML:

  <Window.Resources>
  <Style x:Key="LargeGridStyle" TargetType="{x:Type Grid}">
  <Style.Resources>
  <Style TargetType="{x:Type TextBox}">
  <Setter Property="Template">
  <Setter.Value>
  <ControlTemplate TargetType="{x:Type TextBoxBase}">
  <Border Name="Border" CornerRadius="2" Padding="2" BorderThickness="1.5">
  <Border.Background>
  <SolidColorBrush Color="White" />
  </Border.Background>
  <Border.BorderBrush>
  <SolidColorBrush Color="Blue" />
  </Border.BorderBrush>
  <ScrollViewer Margin="0" x:Name="PART_ContentHost" />
  </Border>
  </ControlTemplate>
  </Setter.Value>
  </Setter>
  </Style>
  </Style.Resources>
  </Style>
  </Window.Resources> 
  <Grid Style="{StaticResource LargeGridStyle}" Height="158" HorizontalAlignment="Left" Margin="35,12,0,0" Name="grid1" VerticalAlignment="Top" Width="336">
  <TextBox Height="23" HorizontalAlignment="Left" Margin="29,21,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
  <TextBox Height="53" HorizontalAlignment="Left" Margin="29,59,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
  </Grid> 
  <TextBox Height="96" HorizontalAlignment="Left" Margin="241,192,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" />
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="385,173,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />

Code Behind:

  private void button1_Click(object sender, RoutedEventArgs e)
  {
  textBox1.BorderBrush = Brushes.Red;
  } 

Answers (1)