Search code examples
c#.netwpfmvvmresourcedictionary

Why doesn't my Textbox react on IsMouseOver in the Style for the ControlTemplate


So I am trying to style my TextBox a little bit, the idea was that I wanted to style the BorderBrush when hovering over the TextBox but for some reason it didnt change the Border, so I tried changing the Background as well, and same thing there. That's when I realized it doesnt react to the IsMouseOver but it does set the background and everything else that I did, it's just the event IsMouseOver that it's not reacting to.

The Control

<TextBox Width="700"
         Height="340"
         HorizontalAlignment="Right"
         Margin="0,0,230,140"
         Foreground="#8bf502"
         TextWrapping="Wrap"
         Style="{DynamicResource TextboxStyle}"/>

The Style

<Style TargetType="{x:Type TextBox}" x:Key="TextboxStyle">
    <Setter Property="OverridesDefaultStyle" Value="True"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="TextBox">
                <Border Background="#424242">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="BorderBrush" Value="Orange"></Setter>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Solution

  • You are missing a TargetName and a BorderThickness:

    <Style TargetType="{x:Type TextBox}" x:Key="TextboxStyle">
        <Setter Property="OverridesDefaultStyle" Value="True"></Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                    <Border Name="border" BorderThickness="2" Background="#424242">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="border" Property="BorderBrush" Value="Orange"></Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    

    There is no Border unless you set the BorderThickness property of it to something else than 0.