编程WPF淡入(通过扩展方法)(Programatically WPF Fade In (via e

2019-10-30 03:57发布

我试图写一个简单的(独立的)C#扩展方法做一个通用的WPF UIElement的淡入,但我找到了解决方案(和代码示例)都含有大量的运动部件(如设置一个故事,等...)

作为参考在这里是我想创建API方法的类型的一个例子。 此代码将根据提供的值旋转一个的UIElement(fromValue,toValue,持续时间和循环)

  公共静态Ť旋转<T>(该T的UIElement,双fromValue,双toValue,整数durationInSeconds,布尔loopAnimation)      其中T:的UIElement  {      返回(T)uiElement.wpfInvoke(              ()=> {                      DoubleAnimation是DoubleAnimation是=新DoubleAnimation是(fromValue,toValue,新持续时间(TimeSpan.FromSeconds(durationInSeconds)));                      RotateTransform rotateTransform =新RotateTransform();                       uiElement.RenderTransform = rotateTransform;                      uiElement.RenderTransformOrigin =新System.Windows.Point(0.5,0.5);                        如果(loopAnimation)                          doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;                      rotateTransform.BeginAnimation(RotateTransform.AngleProperty,DoubleAnimation是);                      返回的UIElement;                  });  } 

Answer 1:

听起来你正在寻找这样的事情:

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;
   });
}


Answer 2:

下面是电网的解决方案。

其中网格是**<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);
            }));


文章来源: Programatically WPF Fade In (via extension methods)