如何从其他线程添加/更新列表视图 [英] How to add/update a listview from a different thread
问题描述
我目前有一种方法可以帮助对自定义项目列表进行排序,然后清除并批量添加更新列表到列表视图。
I currently have a method that helps sort a list of custom items and then clears and mass adds the updated list to a listview.
方法如下所示:
public static void ReLoadLST(bool CanSort, bool UpD, ListView Lst, List<Item> I)
{
Lst.Items.Clear();
int index = 0;
List<Item> AddList = new List<Item>();
if (CanSort && Sort && SearchView.SortBY.Count > 0)
{
try
{
List<Item> LvL1 = new List<Item>();
List<int> UnSotr = new List<int>();
List<int> ASotr = new List<int>();
List<int> NullSotr = new List<int>();
foreach (KeyValuePair<string, string> r in SearchView.SortBY)
{
try
{
bool g = SearchView.PassState[r.Key];
if (g)
{
if (MutiSel.Contains(r.Value))
UnSotr.AddRange(Item.ListNameTag[r.Value][r.Key]);
else ASotr = ASotr.Commons(Item.ListNameTag[r.Value][r.Key]);
}
else NullSotr.AddRange(Item.ListNameTag[r.Value][r.Key]);
}
catch { }
}
UnSotr = UnSotr.Condense();
ASotr = ASotr.Condense();
List<int> Pass = ASotr.Commons(UnSotr);
SortedDictionary<int, Item> tem = Lists.AllList;
if (Pass.Count == 0) Pass = tem.Keys.ToList();
Pass = Pass.RemoveRange(NullSotr);
Pass = Pass.Condense();
//List<int> SeriesAdd = new List<int>();
if (Item.CurrentDetailsMode == Item.DetailsMode.FinStatus)
{
foreach (int x in Pass)
{
try
{
Item i = tem[x];
if (!i.InSeries) AddList.Add(i);
}
catch { }
}
}
else foreach (int x in Pass)
if (x >= 0) try { AddList.Add(tem[x]); } catch { }
}
catch { }
}
else AddList = I;
AddList = AddList.CleanEmtpySeries();
AddList = AddList.SortBy_KnownName();
foreach (Item x in AddList)
{
if (SearchText)
{
string nam = x.KnownName.Trim().RemoveAccents().ToLower();
string ser = SearchView.SearchText.Trim().RemoveAccents().ToLower();
if (!(nam.Contains(ser) || nam == ser))
continue;
}
Item.Itm i = x.LSTItem;
ListViewItem d = new ListViewItem();
d.Content = i;
d.Background = x.BackColor.ToBrush();
d.Foreground = x.ForeColor.ToBrush();
d.Tag = x;
Lst.Items.Add(d);
if (UpD) x.LSTItemIndex = index;
index++;
}
}
如何在不同的线程中运行此方法?
How do I run this method in a different thread?
推荐答案
Ui控件具有线程关联性,您可以使用调度程序与ui线程进行通信,但是您需要运行与ui上的listview或listviewitem交互的代码。
Ui controls have thread affinity, you can use the dispatcher to talk to the ui thread but you need to run code that interacts with a listview or listviewitem on the ui.
Application.Current.Dispatcher.InvokeAsync(new Action(() =>
{
// Do something with UI
}));
如果使用mvvm,你可以绑定一个observablecollection来自viewmodel。
If you used mvvm you could bind an observablecollection from a viewmodel.
然后你可以在一个单独的线程上处理你的绑定数据。
You could then do stuff with your bound data on a separate thread.
一旦你完成,强制ui重读你的界限使用更改通知收集或刷新收集视图。
Once you finish, force the ui to re read your bound collection using change notification or refresh a collectionview.
这篇关于如何从其他线程添加/更新列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!