erodewald
erodewald

Reputation: 1825

Can I update values in an ObservableCollection<T> without destroying and adding new items?

I've got this issue with my WPF application -- I'm using an ObservableCollection<T> to bind the UI to a collection of players. This list gets updated every 10 seconds with new data streamed from a game server. The problem is that blowing away the list and re-adding everything causes for some terrible UI inconsistencies:

So I am asking if there is any way I can update values for an item that don't match the previous value. I do still need it to be DataBinding friendly for the UI (auto updating on PropertyChanged).

Upvotes: 0

Views: 344

Answers (2)

Dan Bryant
Dan Bryant

Reputation: 27515

One option is to extract the Player data into its own class and encapsulate the data in a wrapper. For instance:

public sealed class PlayerData
{
    //Data related to the Player (possibly immutable)
}

public sealed class Player : INotifyPropertyChanged
{
    private PlayerData _data;

    //Mirror properties for information in data

    //Other functionality

    public void ChangeData(PlayerData newData)
    {
        _data = newData;
        //Trigger OnPropertyChanged(null) here to invalidate public state
    }
}

Now you can replace the data for the Player without having to invalidate the outer Player instance. If you look closely, this is actually a kind of ViewModel for the underlying Player model.

Upvotes: 1

Phil Sandler
Phil Sandler

Reputation: 28046

If you can find the players in the collection, you can simply map the updated property values to them. If the player itself implements INotifyPropertyChanged, it should work with very little effort.

Upvotes: 3

Related Questions