Question

I have the below XAML which attempts to set the border of all TextBoxes in the window to red OnMouseOver. What happens is when the mouse is over the textbox the FontSize and Foreground properties are set but the BorderBrush is only set momentarily before reverting to its previous default value. I want the BorderBrush to stay red until the the mouse is no longer over the textbox. Any ideas why this happens?

<Window x:Class="StylesApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Width" Value="250" />
            <Setter Property="Height" Value="50" />
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="FontSize" Value="20" />
                    <Setter Property="Foreground" Value="Red" />
                    <Setter Property="BorderBrush" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <TextBox>
           My TextBox
        </TextBox>
    </Grid>
</Window>
Was it helpful?

Solution

I assume the TextBox has another animation for the BorderBrush when the IsMouseOver property is set to true. However, this trigger is only active when BorderThickness is exactly 1.0. So to overcome this you can change the BorderThickness to 1.01 or something in the trigger and the BorderBrush will stay Red as long as the mouse is over the TextBox.

<Style TargetType="{x:Type TextBox}">
    <Setter Property="Width" Value="250" />
    <Setter Property="Height" Value="50" />
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="BorderThickness" Value="1.01" />
            <Setter Property="FontSize" Value="20" />
            <Setter Property="Foreground" Value="Red" />
            <Setter Property="BorderBrush" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top