How to add animation to margin property of TextBlo

2020-05-04 05:55发布

问题:

I want to make TextBlock like this

But,

aTextBlock.BeginAnimation(Button.MarginProperty, myDoubleAnimation);    

get this error

'System.Windows.Media.Animation.DoubleAnimation' cannot be used to animate the 'Margin' property of type 'System.Windows.Thickness'.

I have test in Xaml and get same error:

<Border CornerRadius="8" Background="Red" Margin="352,173,214,368">
            <TextBlock   x:Name="TestB"
                       Text="{Binding ElementName=MTxt,Path=Text,NotifyOnSourceUpdated=True}"
                      Margin="0,0,0,0"
                        HorizontalAlignment="Center"
                       Foreground="White"
                       FontWeight="Bold"
                       FontSize="16">

                <TextBlock.Triggers>
                    <EventTrigger RoutedEvent="TextBlock.Loaded">                       
                            <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation   
                                    Storyboard.TargetName="TestB"
                                    Storyboard.TargetProperty="(TextBlock.Margin)"
                                    To="2" 
                                    Duration="0:0:1" AutoReverse="True"
                                    RepeatBehavior="2" />
                            </Storyboard>
                        </BeginStoryboard>

                    </EventTrigger>
                </TextBlock.Triggers>

            </TextBlock>
        </Border>

What is your idea?

回答1:

You need to use ThicknessAnimation for this. DoubleAnimation is for properties of Double type.

<TextBlock.Triggers>
    <EventTrigger RoutedEvent="TextBlock.Loaded">
        <BeginStoryboard>
            <Storyboard>
                <ThicknessAnimation   
                    Storyboard.TargetName="TestB"
                    Storyboard.TargetProperty="(TextBlock.Margin)"
                    To="2" 
                    Duration="0:0:1" AutoReverse="True"
                    RepeatBehavior="2" />
            </Storyboard>
        </BeginStoryboard>

    </EventTrigger>
</TextBlock.Triggers>