MVVM ObservableCollection 不工作

MVVM ObservableCollection not working

ObservableCollection 没有更新 UI。

这是我的代码:

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1.ViewModels
{
    public class MainViewModel
    {
        private ObservableCollection<string> strings;

        public MainViewModel()
        {
            strings = new ObservableCollection<string>();
            Add();
        }

        public async void Add()
        {
            for (int i = 0; i < 3; i++)
            {
                await Task.Delay(1000);
                Strings.Add("Item Added");
                Debug.WriteLine("Item Added");
            }
        }

        public ObservableCollection<string> Strings
        {
            get { return strings; }
            set { strings = value; }
        }
    }
}

和视图:

<Window x:Class="WpfApp1.Views.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"                                  
    xmlns:local="clr-namespace:WpfApp1"
    xmlns:ViewModels="clr-namespace:WpfApp1.ViewModels"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <ViewModels:MainViewModel/>
</Window.DataContext>

<Grid>
    <ListBox 
        Name="listBox"
        HorizontalAlignment="Left"
        Margin="10,10,0,10"
        Width="321"
        DataContext="{Binding Strings}"
        />
</Grid>
</Window>

我已经尝试了几个小时来让这个最小的示例正常工作。我以前使用过 MVVM,但现在我没有丢失什么。据我所知,ObservableCollections 已经实现了 INotifyPropertyChanged,所以我的 MainViewModel 没有实现接口(此时)。 也许你可以帮助我,谢谢:.

您想将 collection 绑定到 ItemsSource 属性 而不是 DataContext:

<ListBox 
    Name="listBox"
    HorizontalAlignment="Left"
    Margin="10,10,0,10"
    Width="321"
    ItemsSource="{Binding Strings}"/>