简体   繁体   中英

C# DoubleAnimation Smoothness

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

I'm not sure why the C# code you have is not working as intended but in case XAML code is useful to you here is an example in XAML doing the same. I feel XAML is clearer and more brief. Here I bind the animation to trigger on mouse click on the element for example:

<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>

But you can of course attach it to any other event or invoke the storyboard from code behind by locating it using its resource key like this:

<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>

Invoke like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM