windows8开发笔记(4)消息弹出动画

    Windows8自带了很多动画库,今天我就利用PopInThemeAnimation和PopOutThemeAnimation来做一个消息弹出动画。

首先我们XAML页面添加一个Popup命名为msgPopup用于显示弹出的消息,代码如下:

      <Popup x:Name="msgPopup" Canvas.ZIndex="100" IsOpen="True" Visibility="Collapsed" 
                   Width="200" Height="130" VerticalAlignment="Center" HorizontalAlignment="Center" >
            <Grid Background="Black" Width="200" Height="130">
                <TextBlock x:Name="msgtext" VerticalAlignment="Center" HorizontalAlignment="Center"
                           FontSize="24" Foreground="White" Canvas.ZIndex="1" />
            </Grid>
        </Popup>

我们再在后台添加2个故事版PopIn和PopOut分别是弹出动画和消失的动画,后台定义代码如下

        public Storyboard PopIn { get; set; }

        public Storyboard PopOut { get; set; }

        private void InitStory()
        {
            PopIn = new Storyboard();
            var animationIn = new PopInThemeAnimation();
            Storyboard.SetTarget(animationIn, msgPopup);
            PopIn.Children.Add(animationIn);


            PopOut = new Storyboard();
            var animationOut = new PopOutThemeAnimation();
            Storyboard.SetTarget(animationOut, msgPopup);
            PopOut.Children.Add(animationOut);


            this.PopIn.Completed += PopIn_Completed;
            this.PopOut.Completed += PopOut_Completed;
            this.PopIn.SpeedRatio = (0.5);
            this.PopOut.SpeedRatio = (0.5);
        }

        void PopOut_Completed(object sender, object e)
        {
            this.msgPopup.Visibility = Visibility.Collapsed;
        }

        async void PopIn_Completed(object sender, object e)
        {
            await Task.Delay(388);
            if (this.PopIn.GetCurrentState() == ClockState.Filling)
            {
                this.PopOut.Begin();
            }
        }

 看了这些代码有的人可能很疑惑,那我来解释一下吧,上面代码就是定义PopIn和PopOut是作用在msgPopup上的,一个是PopInThemeAnimation效果另一个是PopOutThemeAnimation效果。其实我的目的就是让PopIn执行的时候把msgPopup显示出来..当PopIn完成之后等待一段时间隐藏msgPopup,我在这里用了Task.Delay(388).意思就是让msgPopup显示388毫秒...这时候再判断下PopIn的状态如果是Filling就让PopOut动画执行完成后隐藏msgPopup。

   知道了原理,代码就很简单了,下面就是利用显示消息的主方法.

        public void ShowMessage(string msg)
        {

  
            this.msgPopup.IsOpen = (true);
            this.msgPopup.Visibility = Visibility.Visible;
            this.PopIn.Begin();
            this.msgtext.Text = (msg);

        }


 

 上面红色圈着的部分就是弹出的消息...过大约388毫秒之后便会消失。附代码

就介绍到这里,欢迎大家留言讨论。

原文地址:https://www.cnblogs.com/cracker/p/windows8_popup.html