调用线程无法访问此对象,因为另一个线程拥有它。甚至在使用调度员之后

时间:2013-09-08 17:41:01

标签: c# wpf wpf-controls dispatcher

在WPF中我有这段代码:

wrapPanel.Dispatcher.Invoke(new Action(() =>
{
    wrapPanel.Children.Add(myCanvas);
}));

当我运行时,我得到了

  

“调用线程无法访问此对象,因为其他线程拥有它”

据我所知,调用dispatcher.Invoke()应解决此问题。

为什么我收到此错误? 可能的原因是什么?

由于我的实际代码太长,我没有把它全部粘贴在这里。顺便说一句,我是个菜鸟。

1 个答案:

答案 0 :(得分:1)

使用WPF时,我们使用通过关联UI对象显示的数据对象。使用Binding,我们通过操作数据对象来更新UI。我会根据您的情况实施类似的操作...首先在DependencyProperty中创建MainWindow.cs以绑定到:

public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
    "Items", typeof(ObservableCollection<Image>), typeof(MainWindow), 
    new UIPropertyMetadata(new ObservableCollection<Image>()));

public ObservableCollection<Image> Items
{
    get { return (ObservableCollection<Image>)GetValue(ItemsProperty); }
    set { SetValue(ItemsProperty, value); }
}

然后添加将显示数据属性的UI代码:

<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

最后,我们必须设置DataContext(这是最少的最佳方式,但这个例子最简单):

public MainWindow()
{
    InitializeComponent();
    DataContext = this;
}

无需任何Dispatcher.Invoke次调用即可实现此目的。