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>

TextBox为什么应用样式后无法更改背景?

<TextBox Style="{StaticResource Border}"
         Background="Bisque"
         Height="77"
         Canvas.Left="184"
         Canvas.Top="476"
         Width="119">Text box</TextBox>
4

2 回答 2

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>

您需要添加以下行:

Background="{TemplateBinding Background}" 

您覆盖了文本框的原始控制模板背景Template的子级。您需要再次将其绑定到目标文本框。

于 2012-11-30T19:04:29.860 回答
0

通过覆盖控件的模板,您实际上是在定义它将如何显示给用户。在您的模板中,您不考虑控件中的任何“设置”,因此它将始终绘制为带有 ScrollViewer 的 Border。

如果要使用控件的属性来自定义模板的某些部分,可以使用将模板内容的属性绑定到控件中的属性TemplateBinding

前任:

<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>

在这种情况下,您将 Border ( Background=) 的 Background 属性绑定到 TextBox ( {TemplateBinding Background)的 Background 属性

因此,总而言之,您在绑定中使用此表示法:

ThePropertyIWantToSet="{TemplateBinding PropertyInMyControl}"
于 2012-11-30T20:02:49.417 回答