在UWP中动画化GradientBrush

时间:2016-11-08 16:58:19

标签: xaml animation uwp gradient

我想为控件的fill属性使用的GradientBrush(在我的例子中为LinearGradientBrush)设置动画。我试图在我的故事板中更改渐变停止值(偏移或颜色),但它似乎不起作用。我为该示例定位了一个网格背景:

<Grid x:Name="LogoGrid" Height="512" Width="512">
    <Grid.Background>
        <LinearGradientBrush x:Name="LogoBackgroundBrush" StartPoint="0 0" EndPoint="1 1">
            <GradientStop x:Name="Stop0" Color="Transparent" Offset="0" />
            <GradientStop x:Name="Stop1" Color="#80FFFFFF" Offset="0.5" />
            <GradientStop x:Name="Stop2" Color="Transparent" Offset="1" />
        </LinearGradientBrush>
    </Grid.Background>
</Grid>

故事板:

<Storyboard x:Key="LoadingStoryBoard">
    <ColorAnimationUsingKeyFrames Storyboard.TargetName="LogoGrid"
            Storyboard.TargetProperty="(UIElement.Background).(LinearGradientBrush.GradientStops)[1].(GradientStop.Color)"
            RepeatBehavior="Forever" EnableDependentAnimation="True">
        <LinearColorKeyFrame Value="#40000000" KeyTime="0:0:1" />
        <LinearColorKeyFrame Value="#A0FFFFFF" KeyTime="0:0:2" />
    </ColorAnimationUsingKeyFrames>
</Storyboard>

2 个答案:

答案 0 :(得分:2)

您确定将EnableDependentAnimation设为true吗?

您可以查看my answer其他类似问题的完整示例。

答案 1 :(得分:0)

您没有提到如何启动故事板。无论如何,我通过将x:Key替换为x:Name使其成功(否则我无法从代码中引用故事板)。

XAML

<Grid x:Name="LogoGrid">
    <Grid.Resources>
        <Storyboard x:Name="LoadingStoryBoard">
            <ColorAnimationUsingKeyFrames
                Storyboard.TargetName="LogoGrid"
                Storyboard.TargetProperty="(UIElement.Background).(LinearGradientBrush.GradientStops)[1].(GradientStop.Color)"
                RepeatBehavior="Forever"
                EnableDependentAnimation="True">
                <LinearColorKeyFrame Value="#40000000" KeyTime="0:0:1" />
                <LinearColorKeyFrame Value="#A0FFFFFF" KeyTime="0:0:2" />
            </ColorAnimationUsingKeyFrames>
        </Storyboard>
    </Grid.Resources>
    <Grid.Background>
        <LinearGradientBrush x:Name="LogoBackgroundBrush" StartPoint="0,0" EndPoint="1,1">
            <GradientStop x:Name="Stop0" Color="Transparent" Offset="0" />
            <GradientStop x:Name="Stop1" Color="#80FFFFFF" Offset="0.5" />
            <GradientStop x:Name="Stop2" Color="Transparent" Offset="1" />
        </LinearGradientBrush>
    </Grid.Background>
</Grid>

代码隐藏

public sealed partial class MainPage
{
    public MainPage()
    {
        InitializeComponent();
        Loaded += (sender, args) => LoadingStoryBoard.Begin();
    }
}

Here is a complete demo project on GitHub

修改

Tangetial:This显示了如何通过x:Key而不是x:Name来访问故事板。诀窍是通过Resources访问故事板,例如:

((Storyboard)Resources["LoadingStoryboard"]).Begin();