WPF:从另一个线程访问UI元素

时间:2015-09-27 19:28:57

标签: c# wpf multithreading user-interface animation

获取System.InvalidOperationException(“调用线程无法访问该对象,因为此对象的所有者是另一个线程。”)在尝试执行动画时。

#carousel {
    width: 100%;
    overflow: hidden;
    height: 600px;
}

#carousel ul {
    width: 3960px;
    padding: 0;
    margin: 0;
    height: 600px;
}

#carousel ul li {
    text-align: center;
    list-style: none;
    float:  left;
}

任何想法?

1 个答案:

答案 0 :(得分:0)

尝试使用以下函数包装函数体:

var dispatcher = Application.Current.Dispatcher;
dispatcher.Invoke( ( Action )( () =>
{

    //your code here

}));

如:

    private void DoPointsShift()
    {
        var dispatcher = Application.Current.Dispatcher;
        dispatcher.Invoke( ( Action )( () =>
        {
            int turnsPerMinute = 5;
            long delay = 60 / turnsPerMinute * 1000 / (360 / 2);
            long deltaDelay = delay;

            int beginTime = Environment.TickCount;
            EasingFunctionBase ease = new CircleEase();
            ease.EasingMode = EasingMode.EaseInOut;
            while (true)
        {
        TimeSpan duration = TimeSpan.FromSeconds(1 - 1 * rnd.NextDouble());
        foreach (var p in points)
        {
            var x = p.OriginX - 50 + rnd.NextDouble() * 100;
            var y = p.OriginY - 50 + rnd.NextDouble() * 100;
            PointAnimation anim = new PointAnimation(new Point(x, y), duration);
            anim.EasingFunction = ease;
            Dispatcher.BeginInvoke(new Action(() =>
            {
                p.BeginAnimation(ParallaxPoint.PointCoordProperty, anim); //exception here
            }));
        }
            while (Environment.TickCount - beginTime < delay) { }
            delay += deltaDelay;
        }
    }));
}

杰夫