C# DoubleAnimation Smoothness

时间:2019-03-06 11:41:27

标签: c# wpf

I'm trying to fade out a UIElement using storyboards and a double animation, the element does indeed fade out but it seems to do it in 2 steps rather than a gradual change in its duration. It looks like it jumps from 1 to 0.5 to 0 with only 3 changes but i would like it to change the opacity a lot more smoother than this.

Here is my current code:

public void fadeout(UIElement target, int targetopac = 0, int fadetime = 1000)
{
    Storyboard FadeOut = new Storyboard();
    DoubleAnimation Fade = new DoubleAnimation();
    Fade.From = target.Opacity;
    Fade.To = targetopac;
    Fade.Duration = TimeSpan.FromMilliseconds(fadetime);
    FadeOut.Children.Add(Fade);
    Storyboard.SetTarget(Fade, target);
    Storyboard.SetTargetProperty(Fade, new PropertyPath("(UIElement.Opacity)"));
    FadeOut.Begin();
}

Edit: The code seems to work perfectly on 64-bit systems but any 32-bit system i try it on the jumps still occur

1 个答案:

答案 0 :(得分:1)

我不确定为什么您拥有的C#代码无法按预期工作,但是如果XAML代码对您有用,这里是XAML中的一个示例。我觉得XAML更清晰,更简短。 在这里,我将动画绑定为在鼠标单击元素时触发,例如:

<Grid Background="Red" >
    <Grid.Triggers>
        <EventTrigger RoutedEvent="MouseDown">
            <BeginStoryboard>
                <Storyboard x:Key="">
                    <DoubleAnimation To="0" Duration="00:00:01" Storyboard.TargetProperty="Opacity" AutoReverse="True" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Grid.Triggers>
</Grid>

但是您当然可以将其附加到任何其他事件,也可以通过使用其资源键来定位故事情节,从而从后面的代码中调用情节提要:

<Grid Background="Red" x:Name="MyGrid">
    <Grid.Resources>
        <Storyboard x:Key="OpacityStoryboard">
            <DoubleAnimation To="0" Duration="00:00:01"
                             Storyboard.Target="{x:Reference Name=MyGrid}"
                             Storyboard.TargetProperty="Opacity"
                             AutoReverse="True" />
        </Storyboard>
    </Grid.Resources>
</Grid>

这样调用:

(MyGrid.Resources["OpacityStoryboard"] as Storyboard).Begin();