2012-03-04 57 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