How to add animation to margin property of TextBlock in WPF

£可爱£侵袭症+ 提交于 2019-12-31 05:41:06

问题


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>


来源:https://stackoverflow.com/questions/23424101/how-to-add-animation-to-margin-property-of-textblock-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!