InvalidOperationException:在ImageOffsetProperty上暂停调度程序处理

时间:2013-10-25 12:05:17

标签: c# wpf dispatcher invalidoperationexception

我正在使用C#和WPF,并尝试在屏幕上滑动图像条。老实说,我从互联网上的一些代码示例中获取了代码并从中获取了我需要的部分。

public double ImageOffset
{
    get
    {
        try
        {
            return (double)this.Dispatcher.Invoke(
               System.Windows.Threading.DispatcherPriority.Background,
               (DispatcherOperationCallback)delegate 
               { return GetValue(ImageOffsetProperty); }, ImageOffsetProperty);
        }
        catch
        {
            return (double)this.GetValue(ImageOffsetProperty);
        }
    }

    set
    {
        this.Dispatcher.BeginInvoke(DispatcherPriority.Background,
            (SendOrPostCallback)delegate 
            { SetValue(ImageOffsetProperty, (object)value); },
            (object)value);
    }
}

有时当程序试图让ImageOffsetProperty发生InvalidOperationException: Cannot perform this operation while dispatcher processing is suspended并且我不知道如何修复它时。

我也试过Dispatcher.BeginInvoke,在Double中保护ImageOffsetProperty然后返回它,但它总是返回0。

导致InvalidOperationException的原因是什么?

1 个答案:

答案 0 :(得分:1)

如何删除所有Background内容并编写一个标准的依赖属性包装器,如下所示:

public double ImageOffset
{
    get { return (double)GetValue(ImageOffsetProperty); }
    set { SetValue(ImageOffsetProperty, value); }
}

当从后台主题设置属性时,请将分配放在Dispatcher.InvokeDispatcher.BeginInvoke来电中。

替换

obj.ImageOffset = someOffset;

通过

Dispatcher.Invoke(() => obj.ImageOffset = someOffset);

Application.Current.Dispatcher.Invoke(() => obj.ImageOffset = someOffset);

如果您无法直接访问某些UI元素的Dispatcher属性。