Gandora
Gandora

Reputation: 368

How to use FadeInAnimation.class in UWP programmatically?

I'm trying to do a simple fade in animation programmatically. In XAML, I have a page with a named Grid inside.

The code behind looks like this:

InitializeComponent();
Button button = new Button() {
    Width = 200,
    Height = 200,
    Content = "Text",
    Background = new SolidColorBrush(Colors.Red)
};
button.Name = "target";

Storyboard myStory = new Storyboard();
FadeInThemeAnimation animation = new FadeInThemeAnimation() {
    BeginTime = new TimeSpan(2),
    Duration = new TimeSpan(4),
};

animation.TargetName = button.Name;
Storyboard.SetTarget(animation, button);
Storyboard.SetTargetProperty(animation, button.Name);

myStory.Children.Add(animation);
myGrid.Children.Add(button);

button.PointerEntered += (s, e) => {
    myStory.Begin();
};

The problem is that I don't see any animation. Also, I'm not sure where to call begin(). Is it best to place in the Loaded event or somehwere else?

Edit: Here is the FadeInThemeAnimation that I'm trying to use.

Upvotes: 0

Views: 305

Answers (1)

Muzib
Muzib

Reputation: 2581

There are a number of problems with your code.

Firstly, in the official doc, FadeInThemeAnimation is described as

preconfigured opacity animation

So, it should increase the Opacity of an UIElement to 1.0 or something like that. But, I believe that the Button you are targeting for the animation already has an opacity 1.0. So, you won't see any change even if the animation is working. So, try a FadeOutThemeTransition instead to test whether your code works or not.

Secondly, you do not set all these things to set the target :

SetTarget, SetTargetName or animation.TargetName =

You just use one of them.

Thirdly, You do not set the Duration property with a new TimeSpan(4). I don't know what type of TimeSpan is returned by the constructor you used, but it doesn' work with that, it works with something like TimeSpan.FromMilliseconds(500).

Fourthly, what are you trying to do with that BeginTime property of FadInThemeAnimation? Even if you are using it on intention, the TimeSpan problem also applies here.

So, after all of that, try something like this:

Storyboard myStory = new Storyboard();
FadeOutThemeAnimation animation = new FadeOutThemeAnimation()
{
    Duration = TimeSpan.FromMilliseconds(500)
};

Storyboard.SetTarget(animation, button);

myStory.Children.Add(animation);
PlayGround.PointerPressed += (kk, kkk) => myStory.Begin();

I've tested it, it works. Hope that helps.

Upvotes: 1

Related Questions