0

我有一个 Threading.timer 在特殊时间显示气球。

我将此代码用于显示气球

 var thread = new Thread(new ThreadStart(DisplayFormThread));

        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();

 private void DisplayFormThread()
{
    try
    {
        Show();
    }
    catch (Exception ex)
    {
        //  Log.Write(ex);
    }
}

这是我的表演气球课。

 if (!Application.Current.Dispatcher.CheckAccess())
    {
        var action = new Action(() => ShowCustomBalloon(balloon, animation, timeout));
        Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, action);
        return;
    }

    if (balloon == null) throw new ArgumentNullException("balloon");
    if (timeout.HasValue && timeout < 500)
    {
        string msg = "Invalid timeout of {0} milliseconds. Timeout must be at least 500 ms";
        msg = String.Format(msg, timeout);
        throw new ArgumentOutOfRangeException("timeout", msg);
    }

    Popup popup = new Popup();
    popup.AllowsTransparency = true;
    popup.PopupAnimation = animation;
    popup.Child = balloon;
    popup.Placement = PlacementMode.AbsolutePoint;
    popup.StaysOpen = true;

    Point position = new Point(SystemParameters.WorkArea.Width - ((UserControl)balloon).Width,
             SystemParameters.WorkArea.Height - ((UserControl)balloon).Height);
    popup.HorizontalOffset = position.X - 1;
    popup.VerticalOffset = position.Y - 1;
    //display item
    popup.IsOpen = true;

当我显示气球时出现错误:调用线程无法访问此对象,因为不同的线程拥有它

在这段代码中我得到错误:

popup.Child = 气球;

4

1 回答 1

1

您不能直接从另一个线程更新 UI。当您在线程中完成并需要更新 UI 时,您可以使用以下内容:

this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (System.Threading.ThreadStart)delegate()
{
    // Update UI properties
});

“this”是一个 UI 元素,例如窗口。您还可以使用:

System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (System.Threading.ThreadStart)delegate()
{
    // Update UI properties
});

而不是引用 UI 组件,即上面示例中的“this”。

于 2012-10-31T09:55:15.327 回答