2015-06-15 81 views
2

語境動畫方法,簡化和修復

我在動畫WPF的東西還挺新的,但我已經有一個或兩個庫周圍打我「有」我與窗口中使用動畫在WPF控件,這是方法的一個例子,請記住,這種方法可行:

public void AnimateFadeWindow(object sender, double opacity, double period) 
    { 
     //Tab item is a enw tab item (the sender is casted to this type.) 

     Window win = (Window)sender; 

     win.Opacity = 0; 

     //using the doubleanimation class, animation is a new isntancem use the parameter opacity and set the period to a timespan. 
     DoubleAnimation animation = new DoubleAnimation(opacity, TimeSpan.FromSeconds(period)); 

     //begin the animation on the object. 
     win.BeginAnimation(Window.OpacityProperty, animation); 
    } 

問題

就像我以前說過,這個代碼工作的概率這個代碼當然只適用於Window控件,它不會與其他控件一起工作,比如TabItem,Button或者其他我想用它的控件,所以我「升級」了我的方法這是我的CURRENT方法:

public void AnimateFade(object sender, double opacity, double period) 
    { 
     //using the doubleanimation class, animation is a new isntancem use the parameter opacity and set the period to a timespan. 
     DoubleAnimation animation = new DoubleAnimation(opacity, TimeSpan.FromSeconds(period)); 

     Object obj = sender.GetType(); 

     if (obj is TabItem) 
     { 
      TabItem tab = (TabItem)sender; 
      tab.BeginAnimation(TabItem.OpacityProperty, animation); 
     } 
     else if (obj is Label) 
     { 
      Label lab = (Label)sender; 
      lab.BeginAnimation(Label.OpacityProperty, animation); 
     } 
     else if (obj is Window) 
     { 
      Window win = (Window)sender; 

      win.Opacity = 0; 
      win.BeginAnimation(Window.OpacityProperty, animation); 
     } 
    } 

此方法不起作用。我真的不知道我在這裏做錯了什麼,所以我想知道是否有人可以幫忙。

另外,有沒有更容易的方法來做到這一點使用像PropertyInfo類或反射類?

謝謝堆棧。

回答

2

您的問題無關Animation。問題是您比較sender.Type而你應該比較sender本身即 使用if (sender is TabItem)代替if (obj is TabItem)

此外,沒有必要一一比較寄件人與TabItem,Lable,Window等,他們都是UIElements!並且由於UIElement實現IAnimatable,你只需要投senderUIElement,你有你的應用動畫任何控制的一般方法:

public void AnimateFade(object sender, double opacity, double period) 
    { 
     UIElement element = (UIElement)sender; 
     element.Opacity = 0; 
     DoubleAnimation animation = new DoubleAnimation(opacity, TimeSpan.FromSeconds(period)); 
     element.BeginAnimation(UIElement.OpacityProperty, animation); 
    } 
+0

真棒,我不知道我可以回溯到UI元素並使用它,這很有趣。 – Method