2012-03-04 25 views
0

我想創建一個計時器,返回到我的WPF應用程序的主菜單,比方說,30秒的不活動。但我得到錯誤「調用線程無法訪問此對象,因爲不同的線程擁有它。」它發生在FadeOut()storyboard.Begin(uc);調用線程無法訪問此對象

我見過一些涉及調用調度員的解決方案,但我不知道如何申請我的情況?

public void ResetScreen() 
{ 
    if (!mainScreen) 
    { 
     Timer myTimer = new Timer(); 
     myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
     myTimer.Interval = 1000; 
     myTimer.Start(); 
    } 
} 

private void OnTimedEvent(object source, ElapsedEventArgs e) 
{ 
    TransitionContent(oldScreen, newScreen); 
} 

private void FadeIn(FrameworkElement uc) 
{ 
    DoubleAnimation dAnimation = new DoubleAnimation(); 
    dAnimation.Duration = new Duration(TimeSpan.FromSeconds(1.0)); 
    dAnimation.From = 0; 
    dAnimation.To = 1; 
    Storyboard.SetTarget(dAnimation, uc); 
    Storyboard.SetTargetProperty(dAnimation, new PropertyPath(OpacityProperty)); 
    Storyboard storyboard = new Storyboard(); 
    storyboard.Children.Add(dAnimation); 
    storyboard.Begin(uc); 
} 

private void FadeOut(FrameworkElement uc) 
{ 
    DoubleAnimation dAnimation = new DoubleAnimation(); 
    dAnimation.Duration = new Duration(TimeSpan.FromSeconds(1.0)); 
    dAnimation.From = 1; 
    dAnimation.To = 0; 
    Storyboard.SetTarget(dAnimation, uc); 
    Storyboard.SetTargetProperty(dAnimation, new PropertyPath(OpacityProperty)); 
    Storyboard storyboard = new Storyboard(); 
    storyboard.Children.Add(dAnimation); 
    storyboard.Begin(uc); 
} 

private void TransitionContent(FrameworkElement oldScreen, FrameworkElement newScreen) 
{ 
    FadeOut(oldScreen); 
    FadeIn(newScreen); 
} 

回答

2

這一條可能是一個解決辦法:

this.Dispatcher.Invoke((Action)(()=>{ 
     // In here, try to call the stuff which making some changes on the UI 
}); 

如:

private void TransitionContent(FrameworkElement oldScreen, FrameworkElement newScreen) 
{ 
    this.Dispatcher.Invoke((Action)(()=>{ 
      FadeOut(oldScreen); 
      FadeIn(newScreen); 
    }); 
} 
+0

此解決方案的工作原理,謝謝。 – Michael 2012-03-06 22:35:10

1

你的問題是,System.Timers.Timer事件在不同的線程比UI運行線。您可以嘗試直接調用其他人提到的方法,也可以使用DispatcherTimer

相關問題