从列表视图获取项目[i]
问题描述:
我想从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();
}
}
我错过了什么?
答
您需要有一个委托类型返回一个字符串,而不是一个空的开始。
然后,您还需要匹配方法来返回一个字符串。
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();
}
}
答
更容易,更可读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;
}
}
感谢您的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
明白了。我所要做的就是将最后一行更改为:return this.lisviewModels.Items [location] .Text – MicroSumol 2011-02-23 17:17:57