以编程方式WPF淡入(通过扩展方法)

时间:2010-06-15 22:57:37

标签: .net wpf animation

我正在尝试编写一个简单的(独立的)C#扩展方法来执行泛型WPF UIElement的淡入淡出,但我发现的解决方案(和代码示例)都包含大量的移动部件(比如设置故事等......)

这里的参考是我想要创建的API方法类型的示例。此代码将根据提供的值旋转UIElement(fromValue,toValue,duration和loop)

public static T rotate<T>(this T uiElement, double fromValue, double toValue, int durationInSeconds, bool loopAnimation)
    where T : UIElement
{
    return (T)uiElement.wpfInvoke(
            ()=>{
                    DoubleAnimation doubleAnimation = new DoubleAnimation(fromValue, toValue, new Duration(TimeSpan.FromSeconds(durationInSeconds)));
                    RotateTransform rotateTransform = new RotateTransform(); 
                    uiElement.RenderTransform = rotateTransform;
                    uiElement.RenderTransformOrigin = new System.Windows.Point(0.5, 0.5);  
                    if (loopAnimation)
                        doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
                    rotateTransform.BeginAnimation(RotateTransform.AngleProperty, doubleAnimation);
                    return uiElement;
                });
}

2 个答案:

答案 0 :(得分:3)

听起来你正在寻找这样的东西:

public static T FadeIn<T>(this T uiElement, int durationInSeconds)
{
  return uiElement.FadeFromTo(0, 1, durationInSeconds, false);
}
public static T FadeOut<T>(this T uiElement, int durationInSeconds)
{
  return uiElement.FadeFromTo(1, 0, durationInSeconds, false);
}

public static T FadeFromTo<T>(this T uiElement,
                              double fromOpacity, double toOpacity,
                              int durationInSeconds, bool loopAnimation)
where T : UIElement
{
  return (T)uiElement.wpfInvoke(()=>
  {
    var doubleAnimation =
      new DoubleAnimation(fromOpacity, toOpacity,
                          new Duration(TimeSpan.FromSeconds(durationInSeconds)));
    if(loopAnimation)
      doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
    uiElement.BeginAnimation(UIElement.OpacityProperty, doubleAnimation);
    return uiElement;
   });
}

答案 1 :(得分:1)

这是Grid的解决方案。

网格为**<Grid Name="RootGrid" Opacity="0">**

的位置
 this.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() =>
            {
                var doubleAnimation = new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(5)));
                RootGrid.BeginAnimation(UIElement.OpacityProperty, doubleAnimation);
            }));