你如何从不同的线程开始故事板?

时间:2013-08-21 19:52:18

标签: c# .net wpf

问题

我正在尝试从不同的线程播放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++;
    }
}

1 个答案:

答案 0 :(得分:1)

将代理放在UI dispatcher上,这会自动将你的东西放到UI线程中。你只能在UI线程上做UI内容。

App.Current.Dispatcher.Invoke((Action)delegate
{
      System.Windows.Media.Animation.Storyboard sb =
            (System.Windows.Media.Animation.Storyboard)FindResource("sbClose");
      BeginStoryboard(sb);
});