XAML使动画平滑

本文关键字:平滑 动画 XAML | 更新日期: 2023-09-27 18:14:17

我正在用ObjectAnimationUsingKeyFrames动画GridColumn宽度属性(GridLength)。我的问题是,是否有可能使动画流畅运行。

<Storyboard
    x:Name="HideOptionsExpandDetails">
    <ObjectAnimationUsingKeyFrames
        Duration="0:0:0.5"
        Storyboard.TargetName="col1"
        Storyboard.TargetProperty="Width">
        <DiscreteObjectKeyFrame KeyTime="0:0:0.5">
            <DiscreteObjectKeyFrame.Value>
                <GridLength>0</GridLength>
            </DiscreteObjectKeyFrame.Value>
        </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames>
</StoryBoard>

基本上这个动画应该使GridLength属性在0.5秒的时间内从300平滑地变为0。但它只是在第5毫秒从300变为0

XAML使动画平滑

这就是ObjectAnimationUsingKeyFrames的工作原理。因为Width是GridLength类型,所以我们不能使用一些内置的动画,比如DoubleAnimation。

那么你可以做的是改变内容的宽度,像这样:

<Page
    x:Class="stofSmoothAnimation.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:stofSmoothAnimation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Page.Resources>
        <Storyboard x:Name="Storyboard1">
            <DoubleAnimationUsingKeyFrames EnableDependentAnimation="True" Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="redBorder">
                <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
    </Page.Resources>
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition x:Name="col1" Width="Auto"/>
            <ColumnDefinition Width="300"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Border x:Name="redBorder" Background="Red" Width="300"/>
        <Border Background="White" Grid.Column="1"/>
        <Border Background="Black" Grid.Column="2">
            <Button x:Name="reduceGridWidth" Click="reduceGridWidth_Click"
                    HorizontalAlignment="Center">
                Button
            </Button>
        </Border>
    </Grid>
</Page>

或者你可以自己处理CompositionTarget来制作动画。像这样呈现事件:

private void reduceGridWidth_Click(object sender, RoutedEventArgs e)
{
    // start handling event
    CompositionTarget.Rendering += CompositionTarget_Rendering;
}
void CompositionTarget_Rendering(object sender, object e)
{
    col1.Width = new GridLength(col1.Width.Value - 20);
    // when the Width hits zero, we stop handling event
    if (col1.Width.Value == 0)
    {
        CompositionTarget.Rendering -= CompositionTarget_Rendering;
    }
}

希望这对你有帮助!