1
votes

I have this List View and a Button:

<ListView x:Name="MyList" ItemsSource="{Binding}" Grid.Row="1"></ListView>
<Button x:Name="Add" Content="Add Item" Click="Add_Click" Grid.Row="2" />

I initialize a list of strings and assign it to the ListView:

List<string> names;

private void FillListView()
{
    names = new List<string>();
    names.Add("Foo");
    MyList.DataContext = names;
}

private void Add_Click(object sender, RoutedEventArgs e)
{
    MyList.Items.Add("Bar");
}

There is also a handler to add one more string to the ListView, but when I click the button, I get Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED)).

I have also try adding the new string directly into the collection, like this:

private void Add_Click(object sender, RoutedEventArgs e)
{
    names.Add("Bar");
}

In this case, ListView is not updated and when I touch it, I get Value does not fall within the exception range 0x80070057.

How do I bind a collection to a ListView and then add more items?

1
Rename the button like this "btnAdd" I suspect button name can generate confusion on compiler - Max

1 Answers

2
votes

Make your additions via your ViewModel, not on the ListView itself, so your code here is dead on:

private void Add_Click(object sender, RoutedEventArgs e)
{
    names.Add("Bar");
}

you just need to change the type of names from List to ObservableCollection so that when items are added/removed, the binding engine is notified and will reflect the changes in the UI.

    ObservableCollection<string> names;

    private void FillListView()
    {
        names = new ObservableCollection<string>();
        names.Add("Foo");
        MyList.DataContext = names;
    }