3
<Style x:Key="Border"
       TargetType="{x:Type TextBox}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TextBox}">
        <Border BorderThickness="1">
          <ScrollViewer Margin="0"
                        x:Name="PART_ContentHost" />
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Why I cannot change TextBox background after applying style?

<TextBox Style="{StaticResource Border}"
         Background="Bisque"
         Height="77"
         Canvas.Left="184"
         Canvas.Top="476"
         Width="119">Text box</TextBox>
Daniel
  • 10,864
  • 22
  • 84
  • 115
Zetian
  • 503
  • 1
  • 3
  • 9

2 Answers2

1
<Style x:Key="Border" TargetType="{x:Type TextBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Border Background="{TemplateBinding Background}" BorderThickness="1">
                    <ScrollViewer Margin="0" x:Name="PART_ContentHost" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

You need to add the following line:

Background="{TemplateBinding Background}" 

You overwrite the original Control Template of textbox. Background is a child of Template. You need to bind it to the target textbox again.

Zetian
  • 503
  • 1
  • 3
  • 9
dongx
  • 1,750
  • 4
  • 17
  • 37
0

By overwriting the template of the control, you are literally defining how it will be shown to the user. In your template, you don't take into account any 'settings' in the control, so it will be always drawn as Border with a ScrollViewer inside.

If you want to use the properties of the control to customize some parts of your template, you can bind properties of your template contents to properties in your control using TemplateBinding

Ex:

<Style x:Key="Border"
       TargetType="{x:Type TextBox}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TextBox}">
        <Border BorderThickness="1"
                Background="{TemplateBinding Background}">
          <ScrollViewer Margin="0"
                        x:Name="PART_ContentHost" />
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

In this case, you are binding the Background property of your Border (Background=) to the Background property of your TextBox ({TemplateBinding Background)

So, in summary, you use this notation in your bindings:

ThePropertyIWantToSet="{TemplateBinding PropertyInMyControl}"
Daniel
  • 10,864
  • 22
  • 84
  • 115
Daniel Castro
  • 1,290
  • 2
  • 11
  • 22