Animation from one style to another.

It’s just interesting if anyone knows how to animate from one style to another, that is, the transition from NormalStyle to ActiveStyle when the user focuses on the text field

<Style x:key="NormalStyle" TargetType="{x:Type TextBox}">
    <Setter Property="BorderBrush" Value="Gray" />
    <Setter Property="BorderThickness" Value="2" />
</Style>

<Style x:key="ActiveStyle" TargetType="{x:Type TextBox}" BasedOn="{StaticResource NormalStyle}">
    <Setter Property="BorderBrush" Value="Green" /> 
    <Setter Property="BorderThickness" Value="4" />
</Style>
+3
source share
1 answer

If you want to change the whole style, I think you might have to do this in code:

<StackPanel>
    <TextBox Style="{StaticResource NormalStyle}" GotFocus="TextBox_GotFocus" LostFocus="TextBox_LostFocus"/>
    <TextBox Style="{StaticResource NormalStyle}" GotFocus="TextBox_GotFocus" LostFocus="TextBox_LostFocus"/>
</StackPanel>
    private Style focusedStyle;
    private Style normalStyle;

    public MainWindow()
    {
        InitializeComponent();

        focusedStyle = FindResource("ActiveStyle") as Style;
        normalStyle = FindResource("NormalStyle") as Style;
    }

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        ((TextBox)sender).Style = focusedStyle;
    }

    private void TextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        ((TextBox)sender).Style = normalStyle;
    }

Otherwise, you are pretty much limited to running back and forth.

<TextBox Text="1" >
        <TextBox.Style>
            <Style BasedOn="{StaticResource NormalStyle}" TargetType="{x:Type TextBox}">
                <Style.Triggers>
                    <EventTrigger RoutedEvent="GotFocus">
                        <BeginStoryboard>
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetProperty="BorderBrush.Color" To="Green" Duration="0:0:0.1" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                    <EventTrigger RoutedEvent="LostFocus">
                        <BeginStoryboard>
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetProperty="BorderBrush.Color" To="Gray" Duration="0:0:0.1" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style
+1
source

Source: https://habr.com/ru/post/1713574/


All Articles