MVVM ObservableCollection不起作用

时间:2018-02-24 22:28:47

标签: wpf mvvm observablecollection

ObservableCollection未更新用户界面。

这是我的代码:

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不实现接口(此时)。 也许你可以帮助我,谢谢:。

1 个答案:

答案 0 :(得分:1)

您希望将集合绑定到ItemsSource属性而不是DataContext

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