Elish
Elish

Reputation: 45

Problem with refreshing a ListView when I add an item from an other window (ObservableCollection)

I have a problem with adding item in my ListView from an another windows, its not added to the list. I am trying to add an item to my ListView that is in my MainWindow from the window WindowTodAddANewBus and I when I add it I would like the MainWindow to be refresh automatically.

Definition of my List in MainWindow.xaml.cs with ObservableCollection

public static List<Bus> buses = new List<Bus>();
public static ObservableCollection<Bus> myCollection { get; set; } = new ObservableCollection<Bus>(buses);

In the constructor:

public MainWindow()
       {
           InitializeComponent();
           myListView.ItemsSource = buses;
       }

When I am adding a new item in WindowToAddANewBus.xaml.cs

Bus b1 = new Bus(myLicenseNum, date);
MainWindow.myCollection.Add(b1);

I don't know if I used well the ObservableCollection..

If you could help me pls!! Thank you

Upvotes: 0

Views: 64

Answers (1)

Bijington
Bijington

Reputation: 3751

You need to set your ItemsSource to your myCollection property and not buses.

To add some context an ObservableCollection does not notify changes to the collection you pass in to the constructor, this is simply a way to place a load of items inside the collection when creating it. It does however notify changes when it's underlying collection changes (e.g. Add, Remove, Clear, etc.). Given this I don't think you even need the buses property at all, you can simply just use your myCollection property.

Basically change your constructor to:

public MainWindow()
{
    InitializeComponent();
    myListView.ItemsSource = myCollection;
}

Possible improvements to general approach

To take things a little bit further you may wish to avoid using a static property entirely as things can certainly get a little messy around these parts. I would suggest looking at either passing your myCollection property over to the WindowToAddANewBus when you create/show it, or better still have that WindowToAddANewBus class return a Bus when it is closed.

Upvotes: 2

Related Questions