在 WPF 中我有这段代码:
wrapPanel.Dispatcher.Invoke(new Action(() =>
{
wrapPanel.Children.Add(myCanvas);
}));
当我运行它时,我得到了
"The calling thread cannot access this object because a different thread owns it"
据我所知,调用 dispatcher.Invoke()
应该可以解决这个问题。
为什么我会收到这个错误? 这可能是什么原因?
由于我的实际代码太长,我没有将其全部粘贴在这里。顺便说一下,我是个菜鸟。
最佳答案
使用 WPF 时,我们使用通过关联 UI 对象显示的数据对象。使用 Binding
,我们通过操作 data 对象来更新 UI。我会针对你的情况实现类似的东西......首先在你的 MainWindow.cs
中创建一个 DependencyProperty
以绑定(bind)到:
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
调用来实现这一点。
关于c# - 调用线程无法访问此对象,因为另一个线程拥有它。即使在使用调度程序之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18686698/