代码Behind中来自Observable集合的Selected Item

时间:2017-04-09 19:53:37

标签: c#

这个主题非常频繁,但我想了解并尽可能得到解决方案。我们如何监听来自一个项目的事件,该项目是从代码背后的可观察集合中选择的。 我写了一个例子:

首先是Personne课程:

public class Personne : INotifyPropertyChanged{
    private int _age = 10;
    public int Age{
       get { return _age; }
       set { _age = value; OnPropertyChanged("Age");  }

       }

    private string _name="";
    public string Name
    {
       get { return _name;  }
       set { _name = value; OnPropertyChanged("Name"); }

    }
    public Personne() { }
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

现在进入主要班级:

 static void Main(string[] args)
    {
        int indice = 0;
        ObservableCollection<Personne> _collection = new ObservableCollection<Personne>();
        _collection.CollectionChanged += _collection_CollectionChanged;
        _collection.Add(new Personne());            
        Personne tmp = _collection[indice];
        indice++;
        tmp.PropertyChanged += Tmp_personne_PropertyChanged;
        tmp.Age = indice;
        _collection.Add(new Personne());
        tmp = _collection[indice];
        indice++;
        tmp.Age = indice;




    }

    private static void _collection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
       int a =1;
        a++;

    }

    private static void Tmp_personne_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        int a = 1;
        a++;
    }
} 

如果我们尝试,第一个

 Personne tmp = _collection[indice];
    indice++;
    tmp.PropertyChanged += Tmp_personne_PropertyChanged;
    tmp.Age = indice;

发射事件,但第二次没有。为什么?

0 个答案:

没有答案
相关问题