我正在尝试创建一个计时器,返回我的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);
}
答案 0 :(得分: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);
});
}
答案 1 :(得分:1)
您的问题是System.Timers.Timer事件在与UI线程不同的线程上运行。您可以尝试直接调用其他人提到的内容,也可以使用DispatcherTimer。