我有很长的单词列表,我先检查单词出现了多少次,然后将其添加到ObservableCollection中。由于它是一个很长的列表,并且迭代需要花费很多时间,所以我希望能够在每次迭代后显示单词,然后继续下一个。当前,在整个集合的迭代完成之后,所有单词将一起显示。
调试时,我注意到在向oWords添加值但未显示该值时,列表框(wordBox)已更新。
Exercise4_btn.Click += async (object sender, RoutedEventArgs e) =>
{
oWords = new ObservableCollection<Word>();
List<string> words = await GetWordsFromFile();
wordBox.DataContext = oWords;
wordBox.SetBinding(ListBox.ItemsSourceProperty, new Binding());
foreach (var word in words)
{
await Task.Run(() =>
{
int count = words.Where(w => w.Equals(word)).Count();
try
{
oWords.Add(new Word {Value = word, Count = count});
}
catch { }
});
}
};
这是列表框在xaml中的外观
<ListBox Name="wordBox" HorizontalAlignment="Left" Height="612" Margin="460,53,0,0" VerticalAlignment="Top" Width="278"/>
这是ObservableCollection使用的类
public class Word
{
public string Value { get; set; }
public int Count { get; set; }
public override string ToString()
{
return ($"{Value}\t{Count}");
}
}
答案 0 :(得分:0)
Coops提供的评论中的链接对我有用 Update UI With WPF Dispatcher And TPL
我还找到了另一个类似的解决方法Asynchronously adding to ObservableCollection