0

特別な時間にバロンを表示するThreading.timerがあります。

このコードをshowBalloonに使用します

 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

You cannot update UI directly from another thread. When you are done in the thread and need to update the UI then you can use following:

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

"this" is a UI element for example the window. You can also use:

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

instead of reference to the UI component i.e. "this" in the example above.

于 2012-10-31T09:55:15.327 に答える