开发者

Observable collection collection changed question

I am learning about observable collections, so I wrote a small program to test my progress. I have a observable collection class that I supply initial values from a list and bind the observablecollection to a Datagrid. It works great, but when I clear the list using myListOfPlayers.myList.Clear(), the Datagrid does not clear. I thought that the INotifyPropertyChanged property would handle that. What am I doing wrong?

public class PlayerList : ObservableCollection<PlayerName> //observable collection class
    {
        public PlayerList()
            : base()
        {
            Clear();

            foreach (var p in myListOfPlayers.myList.OrderBy(x => x.Score))
            {
                Add(p);
            }
        }

        public PlayerList(List<PlayerName> list)
            : base(list)
        {
            Clear();

            foreach (var p in list)
            {
                Add(p);
            }
        }
    }

I implement INotifyPropertyChanged in the PlayerName class:

public class PlayerName : INotifyPropertyChanged
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
       开发者_如何学运维 }

        private int _score;

        public int Score
        {
            get { return _score; }
            set
            {
                _score = value;
                OnPropertyChanged("Score");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }


If you clear myListOfPlayers.myList, the PlayerList is not supposed to be cleared... There is no relation between these 2 lists: you just used myListOfPlayers.myList to initialize the content of PlayerList, but they are two different lists. What you do on one of them doesn't affect the other

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜