問題
我試圖從不同的線程播放StoryBoard,但在WindowsBase.dll中引發'System.InvalidOperationException'。你如何從不同的線索開始故事板?
我有一個自定義控制,InfoBar
,它有一個StoryBoard關閉它和一個System.Timers.Timer
對象要幾秒鐘後這樣做。
那麼,如何從另一個線程調用BeginStoryboard()
?
錯誤消息
扔在BeginStoryboard(sb)
的異常:
An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll but was not handled in user code
Additional information: The calling thread cannot access this object because a different thread owns it.
我(簡化)代碼
private int TimerSeconds;
private System.Timers.Timer t;
public InfoBar()
{
this.InitializeComponent();
TimerSeconds = 0;
t = new System.Timers.Timer(1000);
t.Elapsed += t_Elapsed;
}
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if(TimerSeconds==3)
{
t.Stop();
TimerSeconds = 0;
System.Windows.Media.Animation.Storyboard sb = (System.Windows.Media.Animation.Storyboard)FindResource("sbClose");
BeginStoryboard(sb);
}
else
{
TimerSeconds++;
}
}
我覺得你不能在UI線程之外修改UI的東西。 –