【问题标题】:STA thread in wpfwpf中的STA线程
【发布时间】:2012-09-09 02:10:59
【问题描述】:

我的 ListViewItem 有问题。当我在线程中使用它时,它会显示一条消息:

“调用线程必须是 STA,因为很多 UI 组件都需要这个。”

然后我将其更改为:

Mythread.SetApartmentState(ApartmentState.STA);

虽然我使用它时,它再次显示一条消息:

“调用线程无法访问此对象,因为不同的线程拥有它。”

我使用 Dispatcher。它再次显示一条消息:

“调用线程无法访问此对象,因为不同的线程拥有它。”

我在做什么来解决问题?

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);
}

【问题讨论】:

  • 为什么要在线程上创建 ListViewItem?
  • 因为我想以编程方式将项目添加到 ListView 中。然后我发现它不正确,我不必创建 listviewitem link

标签: wpf multithreading dispatcher sta


【解决方案1】:

如果我理解正确,您想启动一个工作线程来加载某种实体,然后创建一个列表视图项来表示它。

我的猜测是问题在于您正在线程中创建列表视图项,并尝试使用 Dispatcher 将其附加到列表视图。相反,试试这个:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    相关资源
    最近更新 更多