【问题标题】:WPF ListBox not displaying items (one by one)WPF ListBox 不显示项目(一项一项)
【发布时间】:2018-11-25 19:00:06
【问题描述】:

我有一长串单词。我检查单词出现的次数,然后将其添加到 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}");
    }
}

【问题讨论】:

  • 请不要发布您的代码和/或错误消息的屏幕截图(阅读内容:Why not upload images of code on SO when asking a question?An image of your code is not helpfulPictures of exceptions are not helpful)。
  • 谢谢@elgonzo 我已经编辑了我的问题。
  • 嗯...为什么你有一个带有空 catch 块的 try-catch 子句?为什么...?死亡的痛苦更少……;-)
  • 只是为了让我的观点更清楚一点:带有空 catch 块的 try-catch 类似于 Frank Drebin 在这里所做的:youtube.com/watch?v=pdFl__NlOpA ;-)
  • "我注意到列表框(wordBox) 已更新" 您到底注意到了什么?如果你没有看到价值,你看到了什么?另外,你为什么设置ListBox.DataContext 只是为了绑定ListBox.ItemsSource 反对它。我想知道您为什么要这样做,而不是简单地将 ListBox.ItemsSource 设置为集合。

标签: c# wpf xaml


【解决方案1】:

Coops 提供的评论中的链接对我有用 Update UI With WPF Dispatcher And TPL

我还找到了另一个类似的解决方案Asynchronously adding to ObservableCollection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 2018-04-22
    • 1970-01-01
    相关资源
    最近更新 更多