2016-07-23 22 views
2

我已經創建了一個自定義的控件,它從頁面繼承,爲NavigatingFrom事件設置動畫效果。但是,我似乎無法播放實際的動畫。這是我的全部AltPage.cs代碼:自定義Page控件中的動畫組合?

public class AltPage : Page 
{ 
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) 
    { 
     //Set up the composition animation 
     var _compositor = new Compositor(); 
     var _targetVisual = ElementCompositionPreview.GetElementVisual(this); 
     var animation = _compositor.CreateScalarKeyFrameAnimation(); 
     animation.Duration = new TimeSpan(0, 0, 0, 0, 300); 
     animation.InsertKeyFrame(1.0f, 0f); 


     _targetVisual.StartAnimation("Opacity", animation); 

     //Give some time for the animation to start 
     Task.Delay(18); 

     //Get the page to initialize while the animation is playing 
     base.OnNavigatingFrom(e); 
    } 
} 

當我運行的代碼,行_targetVisual.StartAnimation("Opacity", animation)舉起System.UnauthorizedAccessException的。我被告知「調用者不允許在這個對象上執行這個操作」。我究竟做錯了什麼?

回答

1

當我運行代碼時,_targetVisual.StartAnimation(「Opacity」,動畫)行解除System.UnauthorizedAccessException。我被告知「調用者不允許在這個對象上執行這個操作」。

Compositor對象需要從當前頁面的任何Visual獲得。您可以使用下面的代碼有一個排字:

ElementCompositionPreview _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor; 

Page.OnNavigatingFrom導航之前提出的,但我們不能給出一個延遲阻止該網頁導航。當我們使用Task.Delay時,我們需要一個await來讓它同步工作。但它會使整個功能異步運行(使用await時將添加async)。所以,如果你把你的密碼在OnNavigatingFrom,你不會得到預期的行爲

作爲一種變通方法,你可以把你的代碼Frame.Navigate前象下面這樣:

Compositor _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor; 
Visual _targetVisual = ElementCompositionPreview.GetElementVisual(this); 
var animation = _compositor.CreateScalarKeyFrameAnimation(); 
animation.Duration = new TimeSpan(0, 0, 0, 0, 3000); 
animation.InsertKeyFrame(0.0f, 1.0f); 
animation.InsertKeyFrame(1.0f, 0.0f); 

_targetVisual.StartAnimation("Opacity", animation); 
await Task.Delay(3000);//Give some time for the animation to start 
Frame.Navigate(typeof(NewPage)); 

因此,你會得到頁衰落的動畫,我也做了一個演示,你可以參考:CustomPageSample

+0

@ user2950509嗨,這個話題的任何更新? –