2011-02-23 181 views
0

我想從ListView中獲取一個項[i]到一個字符串。當ListView在另一個線程上時,我似乎並不明白我應該做什麼。從列表視圖獲取項目[i]

public delegate void getCurrentItemCallBack (int location); 
... 
private void runAsThread() 
{ 
    While (..>i) 
    { 
    //I tried the following //Doesn't work. 
    //string item_path = listView.Item[i].toString(); 

    //attempting thread safe. How do I get it to return a string? 
    string item_path = GetCurrentItem(i); 
    } 
} 
private void GetCurrentItem(int location) 
{ 
    if (this.listViewModels.InvokeRequired) 
     { 
     getCurrentItemCallback d = new getCurrentItemCallback(GetCurrentItem); 
     this.Invoke(d, new object[] { location }); 
     } 
     else 
     { 
     this.listViewModels.Items[location].ToString(); 
     } 
} 

我錯過了什麼?

回答

3

您需要有一個委託類型返回一個字符串,而不是一個空的開始。

然後,您還需要匹配方法來返回一個字符串。

public delegate string getCurrentItemCallBack (int location); 

... 

private string GetCurrentItem(int location) 
{ 
    if (this.listViewModels.InvokeRequired) 
     { 
     getCurrentItemCallback d = new getCurrentItemCallback(GetCurrentItem); 
     return this.Invoke(d, new object[] { location }); 
     } 
     else 
     { 
     return this.listViewModels.Items[location].ToString(); 
     } 
} 
+0

感謝您的relply瞎搞。在你的線上: return this.Invoke(d,new object [] {location}); 我將它改爲: return this.Invoke(d,new object [] {location})。ToSring();因爲我得到一個錯誤。 這有效,但是當我查看返回的字符串時,它包括:「ListViewItem:{C:\ test.txt}」。 有沒有辦法只是返回C:\ test.txt – MicroSumol 2011-02-23 16:46:05

+0

明白了。我所要做的就是將最後一行更改爲:return this.lisviewModels.Items [location] .Text – MicroSumol 2011-02-23 17:17:57

0

更容易,更可讀IMO使用lambda行動,沒有與回調或委託

private void GetCurrentItem(int location) 
    { 
     if (this.listViewModels.InvokeRequired) 
     { 
      Invoke(new Action()=>{ 
       //do what ever you want to do here 
       // this.listViewModels.Items[location].Text; 
      })); 
     } 
     else 
     { 
      this.listViewModels.Items[location].Text; 
     } 
    }