Search code examples
wpfxamltextboxcontroltemplate

WPF XAML TextBox not editable after applying Control Template


I have a TextBox in WPF and I'm trying to make the border color change when the mouse hovers over the TextBox. Based on my experience with other elements in WPF, I need to insert a ControlTemplate value with TemplateBinding to the values I am trying to dynamically change. However, when I apply this, the box becomes uneditable (and the text disappears). If I remove the Template setter, the box becomes editable again, but the custom BorderBrush triggers do not work.

Here is the Style:

<Style x:Key="TextBoxBase" TargetType="TextBox">
    <Setter Property="FontSize" Value="30"/>
    <Setter Property="Background" Value="{StaticResource BrushLightGrey}"/>
    <Setter Property="Foreground" Value="{StaticResource BrushNormalText}"/>
    <Setter Property="IsReadOnly" Value="False"/>
    <Setter Property="Height" Value="40"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Border BorderBrush="{TemplateBinding BorderBrush}">
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="BorderBrush" Value="{StaticResource BrushBlue}"/>
        </Trigger>
    </Style.Triggers>
    <Style.Resources>
        <Style TargetType="{x:Type Border}">
            <Setter Property="CornerRadius" Value="5"/>
        </Style>
    </Style.Resources>
</Style>

Any suggestions or help is appreciated. Thanks.


Solution

  • You missed out the critical part:

          <ScrollViewer Margin="0"
                        x:Name="PART_ContentHost" />
    

    This is what hosts the text.

    See

    https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/textbox-styles-and-templates

    TextBox Parts The following table lists the named parts for the TextBox control.

    TEXTBOX PARTS Part Type Description PART_ContentHost FrameworkElement A visual element that can contain a FrameworkElement. The text of the TextBox is displayed in this element.