0

I'm making an API which is will be use my chat program.

API core class have a room list like a List<Room> Rooms_;

API core class have a property. public Room[] Rooms { get { return Rooms_.ToArray(); } }

and API core class also have a property which is easily to print room list. This property is public ObservableCollection<Room> ObservableRooms { get { return new ObservableCollection<Room>(Rooms_); }

Now, when room is added or removed, i coded Add function and Remove function like this.

Rooms_.Add(new_room);
Rooms_.Remove(room);

but the ObservableRooms dosen't change automatically.

I want to bind ObservableRooms property to the Rooms_ list.

Anyone know this?

Thanks.

11
  • I don't think having a property returning an new ObservableCollection with each call to get makes sense, but I'm not a WPF expert.
    – Dirk
    Sep 3, 2014 at 6:03
  • @Dirk No, it is a not WPF. just change value automatically :) hmm.. Sep 3, 2014 at 6:05
  • @Dirk an ObservableCollection has a constructor (List<T>) but is this wrong? Sep 3, 2014 at 6:06
  • 1
    ObservableCollection just copies the elements from List<T> passed in constructor. It doesn't uses it internally. Sep 3, 2014 at 6:09
  • The point is that an observable collection is a collection, it stores the values you add and does not rely on any external collection. Initializing it with a list/enumerable simply makes a copy of that list for internal purposes. If you change the original list then the ObservableCollection won't know that.
    – Dirk
    Sep 3, 2014 at 6:10

1 Answer 1

1

If you are binding directly to the ObservableCollection why not manipulate the ObservableCollection directly.

private ObservableCollection<Room> _observableRooms

public ObservableCollection<Room> ObservableRooms 
{
    get { return _observableRooms; }
    set { _observableRooms = value; }
}

Then add and remove directly from ObservableRooms and your UI should update correctly.

1
  • I would also make the setter private, unless you want users of that API to change the entire collection instead of just adding/deleting items.
    – Dirk
    Sep 3, 2014 at 7:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.