I have a WPF DataGrid who’s data source is an ObservableCollection. It is set up loosely as the following:
public class ItemDataCollection : ObservableCollection<ItemData>
{
}
public class ItemData : INotifyPropertyChanged
{
private bool _selected = true;
public bool Selected
{
get
{
return _selected;
}
set
{
if (value != _selected)
{
_selected = value;
NotifyPropertyChanged("Selected");
}
}
}
}
_itemDataCol = new ItemDataCollection();
<... fill the _itemDataCol with data here ...>
dataGrid1.ItemsSource = _itemDataCol;
When the collection is updated, a dataGrid1.Items.Refresh() updates dataGrid1 nicely. However when I modify the “Selected” property of a row by checking or unchecking the checkbox in the row corresponding to that property, the item in the collection does not get updated. I looked into the CollectionChanged event of the ObeservableCollection, but that is not appearing to get triggerd. What wiring do I need to get the dataGrid1 to update the collection.
Update
All I was doing was setting the ItemSource property to the ObservableCollection and letting the columns auto-generate. I have since changed to bind directly, and found more detail to the problem. When I simply check the box – no notification is triggerd. However if I hit after checking the box, then the collection is updated. Here is the binding:
<DataGridCheckBoxColumn Binding="{Binding Path=Selected, Mode=TwoWay}" Header="Selected"></DataGridCheckBoxColumn>
So I guess the question is how do I get the update with having to hit after checking or unchecking the box?
Update #2
(I cannot answer as my rep is not high enough yet)
OK – I think I have the solution. If I include “UpdateSourceTrigger=PropertyChanged” in the binding everything seems to work.
<DataGridCheckBoxColumn Binding="{Binding Path=Selected, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Header="Selected"></DataGridCheckBoxColumn>
Please leave comments if there are any negative affects of this that I may be missing. Thanks for the help!
CollectionChanged is for Insert and Delete. NotifyPropertyChanged is for update of an items. In the posted code you don’t actually implement INotifyPropertyChanged.
And I think it is cleaner to bind to a public property where you return _itemDataCol
Otherwise the TwoWay answer of celopez3