开发者

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:

  • selected items become deselected
  • context menus open become unbound and useless
  • pos开发者_如何学运维sibly some errors cropping up from all the item instances being lost

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).


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜