2013-07-25 8 views
0

У меня есть следующий фрагмент кода для создания ObservableCollection, привязанного к DataGrid.Коллекция изменила событие для дочернего объекта

public class Test:INotifyPropertyChanged 
    { 

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

     private string _city; 
     public string City 
     { 
      get { return _city; } 
      set 
      { 
       _city = value;OnpropertyChanged("City");} 
     } 


     #region INotifyPropertyChanged Members 

     public event PropertyChangedEventHandler PropertyChanged; 
     public void OnpropertyChanged(string propertyName) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) 
      { 
       var e = new PropertyChangedEventArgs(propertyName); 
       handler(this, e); 
      } 
     } 
     #endregion 
    } 

class Data:INotifyPropertyChanged 
    { 

     private int customerID; 

     public int CustomerID 
     { 
      get { return customerID; } 
      set { customerID = value; OnpropertyChanged("CustomerID"); } 
     } 

     private bool isSelected; 

     public bool IsSelected 
     { 
      get { return isSelected; } 
      set { isSelected = value; OnpropertyChanged("IsSelected"); } 
     } 

     private ObservableCollection<Test> _collection; 
     public ObservableCollection<Test> Collection 
     { 
      get { return _collection; } 
      set { _collection = value;OnpropertyChanged("Collection" + 
                 ""); } 
     } 
     public event PropertyChangedEventHandler PropertyChanged; 

     public void OnpropertyChanged(string propertyName) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) 
      { 
       var e = new PropertyChangedEventArgs(propertyName); 
       handler(this, e); 
      } 
     } 


    } 
class ViewModel:NotificationObject 
{ 
    public ViewModel() 
    { 
     this.GDCSource = Getsource(); 
    } 

    private ObservableCollection<Data> _gdcsource; 

    public ObservableCollection<Data> GDCSource 
    { 
     get { return _gdcsource; } 
     set { _gdcsource = value; RaisePropertyChanged("GDCSource");} 
    } 




    private ObservableCollection<Data> Getsource() 
    { 
     ObservableCollection<Data> items = new ObservableCollection<Data>(); 
     if (items != null) 
     { 
      items.Add(new Data() 
       { 
        IsSelected = true, 
        CustomerID = 1, 
       }); 
      items.Add(new Data() 
       { 
        IsSelected = true, 
        CustomerID = 2, 
       }); 
     } 
     return items; 

    } 
} 

public partial class MainWindow : Window 
    { 

     public MainWindow() 
     { 
      InitializeComponent(); 
      ViewModel vmModel = new ViewModel(); 
      this.datagrid.ItemsSource = vmModel.GDCSource; 
      vmModel.GDCSource.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(GDCSource_CollectionChanged); 
     } 

     void GDCSource_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) 
     { 
      //Listen the collection changed event for underlying source 
     } 

     // add the object to the Collection property 
     private void Test_OnClick(object sender, RoutedEventArgs e) 
     { 
      (this.DataContext as ViewModel).GDCSource[0].Collection.Add(new Test() { Name = "Name1", City = "City1" }); 
      (this.DataContext as ViewModel).GDCSource[0].Collection.Add(new Test() { Name = "Name1", City = "City1" }); 
      (this.DataContext as ViewModel).GDCSource[0].Collection.Add(new Test() { Name = "Name1", City = "City1" }); 
     } 
    } 

Можно прослушивать при добавлении свойства Collection в любом случае.

Заранее спасибо

С уважением, Rajasekar

ответ

0

Если вы имеете в виду вы хотите зарегистрировать событие, которое возникает при добавлении элемента/удалена в наблюдаемой коллекции вы должны смотреть на CollectionChanged событии

ObservableCollection<T>.CollectionChanged Event

Происходит, когда предмет добавлен, удален, изменен, перемещен или весь список обновлен.

0

Вы можете расширить свою собственную версию ObservableCollection, если вы хотите, и переопределить метод добавления,

Там вы можете уволить любые делегат или все, что вы можете зарегистрировать, пользовательский интерфейс будет автоматически обновляться с помощью ObservableCollection с элементами добавлено/удалено, вам ничего не нужно делать,

Смежные вопросы