I have a long list of words.I check how many times the word occurs then I add it to an ObservableCollection.Since it is a long list and the iteration takes quite a bit of time, I would like to be able to display the word after each iteration and continue to the next. Currently the words will be displayed all together after the iteration of the whole collection is done.
When debugging I noticed that the listbox(wordBox) was updated when I added a value to oWords but the value was not displayed.
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 { }
});
}
};
This is how the listbox looks in xaml
<ListBox Name="wordBox" HorizontalAlignment="Left" Height="612" Margin="460,53,0,0" VerticalAlignment="Top" Width="278"/>
And this is the class used by the ObservableCollection
public class Word
{
public string Value { get; set; }
public int Count { get; set; }
public override string ToString()
{
return ($"{Value}\t{Count}");
}
}