为什么我不能在应用样式后更改文本框背景?

时间:2012-11-30 19:02:06

标签: wpf xaml textbox styles

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

2 个答案:

答案 0 :(得分: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}" 

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

答案 1 :(得分: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的Background属性({TemplateBinding Background

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

ThePropertyIWantToSet="{TemplateBinding PropertyInMyControl}"
相关问题