分派器不会更新ListBox控件

时间:2019-08-31 18:42:54

标签: c# .net wpf

这是列表框本身:

...
    <Window.Resources>
        <DataTemplate x:Key="ListBoxTemplate" DataType="ArticlesApp:Article">
            <StackPanel Margin="6, 10, 0, 0" Height="45">
                <DockPanel>
                    <TextBlock Text="{Binding Title}" FontWeight="Bold"/>
                </DockPanel>
                <DockPanel>
                    <TextBlock Text="{Binding Author, StringFormat='by {0}'}"/>
                </DockPanel>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
...
<ListBox Grid.Row="0" x:Name="ListBox" SelectionChanged="ListBox_OnSelectionChanged" Background="#444444" SelectionMode="Single" ItemTemplate="{StaticResource ListBoxTemplate}"/>

然后分派器在后面的代码中

        public ArticlesView()
        {
            InitializeComponent();

            ...

            Dispatcher?.BeginInvoke(new Action(() => { ListBox.ItemsSource = GetArticles(); }), DispatcherPriority.Background);
        }

        public static List<Article> GetArticles()
        {
            var articles = new List<Article>();

            foreach (string file in Directory.GetFiles("articles", "*.json", SearchOption.AllDirectories))
            {
                File.OpenText(file);

                articles.Add(JsonConvert.DeserializeObject<Article>(File.ReadAllText(file)));
            }

            return articles;
        }

它可以在应用程序启动时工作,将ListBox的ItemSource分配给GetArticles,但是如果有任何更改,它什么也不做。

1 个答案:

答案 0 :(得分:-1)

使用ObservableCollection而不是Using List,以便无论何时更改源,它都会自动触发INotifyPropertyChange和INotifyCollectionChange,并且itemsource将从集合中重新获取。

public static ObservableCollection<Article> GetArticles()
    {

        var articles = new ObservableCollection<Article>();

        foreach (string file in Directory.GetFiles("articles", "*.json", SearchOption.AllDirectories))
        {
            File.OpenText(file);
            articles.Add(JsonConvert.DeserializeObject<Article>(File.ReadAllText(file)));
        }

        return articles;
    }