سؤال

I have a problem with ListViewItem.When i use it in a thread, it display a message:

"The calling thread must be STA, because many UI components require this."

and then I change it to :

Mythread.SetApartmentState(ApartmentState.STA);

Although when I use it, it display a message again:

"The calling thread cannot access this object because a different thread owns it."

I use Dispatcher for it. It display a message again:

"The calling thread cannot access this object because a different thread owns it."

what am I doing to solve problem?

Thread th = new Thread(() =>
    {                                          
        search.SearchContentGroup3(t, addressSearch.CurrentGroup.idGroup);
    });
th.SetApartmentState(ApartmentState.STA);
th.Start();


public void SearchContentGroup3(int id)
{
    ListViewItem lst = new ListViewItem();
    lst.DataContext = p;        
    Application.Current.Dispatcher.BeginInvoke(
        new Action(() => currentListView.Items.Add(lst)),
        DispatcherPriority.Background);
}
هل كانت مفيدة؟

المحلول

If I understand correctly, You want to kick off a worker thread to load an entity of some sort, then create a list view item to represent it.

My guess would be that the issue is you're creating the list view item in the thread, and attempting to attach it to the list view using the Dispatcher. Instead, try this:

public void SearchContentGroup3(int id)
{
// Do stuff to load item (p?) 
// ...

// Signal the UI thread to create and attach the ListViewItem. (UI element)
Application.Current.Dispatcher.BeginInvoke(
    new Action(() => 
    {
       var listItem = new ListViewItem() {DataContext = p};
       currentListView.Items.Add(lst); 
    }),
    DispatcherPriority.Background);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top