Janine Alexander
Janine Alexander

Reputation: 161

Allow users to add multiple items to ObservableCollection c#

I have a ListView that should populate based on user inputs. The ListView is binded to my ObservableCollection. When user adds an item, it inserts but immediately after when I do another add, the previous item is removed and replaced with the latest added item(Making the list items 1 instead of 2). How can I fix this?

Code:

public ObservableCollection<string> Items { get; set; }

 private void Button_Clicked(object sender, EventArgs e)
        {
            Items = new ObservableCollection<string>
            {
                TxtEntry.Text
            };


            MyListView.ItemsSource = Items;
        }

Upvotes: 0

Views: 1320

Answers (2)

Gerald Versluis
Gerald Versluis

Reputation: 34063

It's because you are creating a new collection each time.

Change your code like this:

public ObservableCollection<string> Items { get; set; } = new ObservableCollection<string>();

public YourConstructor()
{
   MyListView.ItemsSource = Items;
}

private void Button_Clicked(object sender, EventArgs e)
{
    Items.Add(TxtEntry.Text);
}

What you see happening here is the collection is instantiated when the property is created for the first time.

Then, in the constructor of your object, set the ItemSource of the ListView to the ObservableCollection and then whenever the button is clicked, simply add the item, instead of creating a whole new collection each time.

Also, you don't need to set the ItemSource each time. Because it is an ObservableCollection the ListView will be notified of any changes in the collection.

Upvotes: 3

Luca
Luca

Reputation: 1826

You should add it to the list, not re-create the list:

public ObservableCollection<string> Items { get; set; }

private void Button_Clicked(object sender, EventArgs e)
{
    if(Items == null) 
    {
        Items = new ObservableCollection<string>
        {
            TxtEntry.Text
        };
    } 
    else {
        Items.Add(TxtEntry.Text);
    }
    MyListView.ItemsSource = Items;
}

Upvotes: 1

Related Questions