samedi 28 février 2015

Winforms MVVM GridView DataBinding

I am trying to bind a GridView using a BindingList<T> in an MVVM pattern.


In my code, I bind the gridview as follows:



BindingSource bindingSource = new BindingSource(Context.MyList, null);
bindingSource.CurrentChanged += Context.BindingSourceCurrentItemChanged;
// NOTE: this part is to test if the event is fired...
Context.MyList.ListChanged += myList_ListChanged;
myGrid.DataSource = bindingSource;


I have an add button that calls a method in the Context as an ICommand:



Context.myCommand.Execute(null);


Finally, in the command itself (which is in the Context class), I do the following:



MyList.Add(new Item());


Pretty straight forward implementation... The bindingSource.CurrentChanged does fire properly, but I never enter the myList_ListChanged event.


If I stop on the launching of the ICommand and add several items, the Context.MyList count is indeed updated. Same occurs with if I use delete command...


Is there anything obvious I am missing here ???


Thanks in advance, N.


EDIT I realized that for the problem comes from the fact I have MyList as a property as follows:



BindingList<T> myList;
public BindingList<T> MyList {
get {
if (myList == null) { myList = new BindingList<T>();}
return myList;
}
}


I create the BindingSource in the form's constructor, whereas I have the following code called in the ViewModel AFTER the binding is made:



myList = new BindingList<T>
RaisePropertyChanged("MyList");


I know this is WPF thinking, where this would update data bindings seamlessly.


As I understand this, BindingSource doesn't seem to listen to the changes of the datasource itself (i.e. the pointer to the object), as opposed to changes of its content.


Would anyone be kind enough to confirm this behavior? Thanks! N.


Aucun commentaire:

Enregistrer un commentaire