Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
&引用;调用线程无法访问此对象,因为其他线程拥有它";C#WPF应用程序中出现错误?_C#_.net_Wpf_Xaml_Listbox - Fatal编程技术网

&引用;调用线程无法访问此对象,因为其他线程拥有它";C#WPF应用程序中出现错误?

&引用;调用线程无法访问此对象,因为其他线程拥有它";C#WPF应用程序中出现错误?,c#,.net,wpf,xaml,listbox,C#,.net,Wpf,Xaml,Listbox,我正在做一个下载程序。在我的项目中有名为main.xaml.cs和downloader.cs的主窗口和下载程序类 主窗口中有一个自定义列表框。我试图从Downloader.cs刷新Listbox项,但应用程序给出了“调用线程无法访问此对象,因为另一个线程拥有”错误 Downloader.cs: namespace MyDownloaderApp { class Downloader { /* ... */ priv

我正在做一个下载程序。在我的项目中有名为main.xaml.cs和downloader.cs的主窗口和下载程序类

主窗口中有一个自定义列表框。我试图从Downloader.cs刷新Listbox项,但应用程序给出了“调用线程无法访问此对象,因为另一个线程拥有”错误

Downloader.cs:

namespace MyDownloaderApp
{
    class Downloader
    {
        /*
        ...
        */

        private void doWork()
        {
            ((MainWindow)System.Windows.Application.Current.MainWindow).myListBox.Items.Refresh();
        }
    }
}
An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll but was not handled in user code: "The calling thread cannot access this object because a different thread owns it."
我收到以下错误:

namespace MyDownloaderApp
{
    class Downloader
    {
        /*
        ...
        */

        private void doWork()
        {
            ((MainWindow)System.Windows.Application.Current.MainWindow).myListBox.Items.Refresh();
        }
    }
}
An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll but was not handled in user code: "The calling thread cannot access this object because a different thread owns it."
导致此错误的原因以及我如何修复它?

您应该使用:

this.Dispatcher.Invoke((Action)(() =>
    {
        ...// your code refresh listbox Items
    }));

请查看:

正确的方法是使用绑定,而不是直接操作列表框。而且会很有用。我已经在使用绑定了。我想在向列表框添加数据后刷新列表框项目。然后,使用
ObservableCollection
BindingOperations.EnableCollectionSynchronization
,它会自动更新。您可以使用
this.Dispatcher.BeginInvoke
而不是
this.Dispatcher.Invoke