Noodlephile
Noodlephile

Reputation: 27

Binding ObservableCollection to ListBox ItemsSource

I'm having some trouble getting my ListBox to update from changes to my ObservableCollection. I bound the ItemsSource of my ListBox to the ObservableCollection, yet the ListBox still refuses to show anything.

If I implement INotifyPropertyChanged, and raise a property changed event whenever I change the collection, it works. But I thought that I wouldn't have to do that if I was using an ObservableCollection.

What should I do to make the ListBox update and show the ObservableCollection appropriately?

Xaml:

<Window x:Name="window" x:Class="testApp.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:testApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525" DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}">
    <StackPanel Margin="0">
        <Button Content="Add" HorizontalAlignment="Left" Height="24" Margin="5,5,0,0" Width="100" Click="Button_Click"/>
        <ListBox Height="140" Margin="5,5,5,0" VerticalAlignment="Top" ItemsSource="{Binding MyStrings, ElementName=window}"/>
    </StackPanel>
</Window>

Code-behind:

namespace testApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MyStrings = new ObservableCollection<string> { "Boop" };
        }

        public ObservableCollection<string> MyStrings { get; private set; }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MyStrings.Add("New String");
        }
    }
}

Upvotes: 2

Views: 1705

Answers (1)

ASh
ASh

Reputation: 35733

put MyStrings = new ObservableCollection<string> { "Boop" }; line before InitializeComponent();

public MainWindow()
{
    MyStrings = new ObservableCollection<string> { "Boop" };
    InitializeComponent();
}

with current code binding in ItemsSource="{Binding MyStrings}" reads MyStrings before it is initialized and needs notification to update MyStrings when collection is created.

without notification ItemsSource stays null.

Upvotes: 2

Related Questions