views:

32

answers:

3

I am binding a WPF application DataGrid to an ObservableCollection via the DataGrid's "ItemSource". Initially the DataGrid does come up with headings and values, however the upgrades made to the ObservableCollection are not reflected? (i.e. when I come back programmatically and increase the "Total" value) The ObservableCollection I am using is below.

Any ideas why & how to get the grid to dynamically update/bind correctly?

public class SummaryItem
{
    public string ProcessName { get; set; }
    public long Total { get; set; }
    public long Average { get; set; }

    public static SummaryItem ObservableCollectionSearch(ObservableCollection<SummaryItem> oc, string procName)
    {
        foreach (var summaryItem in oc)
        {
            if (summaryItem.ProcessName == procName) return summaryItem;
        }
        return null;
    }
}

EDIT - Or perhaps an add-on question is whether in this case DataGrid isn't the control I should be using to visualize what is effectively an in-memory table? That is the observableCollection of SummaryItem's is effectively the in-memory table.

+1  A: 

you have just ran into the classic problem with ObservableCollection. Only item add and item remove events are fired for OC. That means, if an item changes, you do NOT get an "ItemChanged" event.

Muad'Dib
+2  A: 

If I see it right you are using an ObservableCollection. If you add items to the ObservableCollection these changes should always been reflected by WPF, but if you edit properties on an item (i.e. changing the "Total" value of a SummaryItem) this is no change to the ObservableCollection but to the SummaryItem.

To achieve the desired behaviour your SummaryItems have to implement the INotifyPropertyChanged interface to "notify" WPF when propertys are changed:

// implement the interface
public event PropertyChangedEventHandler PropertyChanged;

// use this for every property
private long _Total;
public long Total {
    get {
        return _Total;
    }
    set {
        _Total = value;
        if(PropertyChanged != null) {
            // notifies wpf about the property change
            PropertyChanged(this, new PropertyChangedEventArgs("Total"));
        }
    }
}
Jens Nolte
+1  A: 

This thread should be useful.

Thanks, Damian

Damian Schenkelman