Bob_Foo
Bob_Foo

Reputation: 23

MVVM ObservableCollection not working

An ObservableCollection is not updating the UI.

Here is my code:

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; }
        }
    }
}

And the View:

<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>

I have been trying several hours to get this minimal example working. I've used MVVM before but now I don't get whats missing. From what I know, the ObservableCollections already implements INotifyPropertyChanged, so my MainViewModel doesn't to implement the interface (at this point). Maybe you can help me, thanks :.

Upvotes: 0

Views: 40

Answers (1)

Karolis Kajenas
Karolis Kajenas

Reputation: 1543

You want to bind your collection to ItemsSource property instead of DataContext:

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

Upvotes: 1

Related Questions