Search code examples
c#wpfdatagridobservablecollection

C# how to bind a datagrid t observableCollection of classes with observable collections using code behind


I have a datagrid which has to be associated to an observable collection of the following class:

public class CfgCounters
{
    public int valuePresent { get; set; }
    public string Name { get; set; }
    public ObservableCollection<DateTime> obcDatetime { get; set; }
    public ObservableCollection<string> obcLastExecutedPP { get; set; }
    public ObservableCollection<int> obcNumDimsOK { get; set; }
}

I have therefore

ObservableCollection<CfgCounters> obcCounters = new ObservableCollection<CfgCounters>();

which I fill with instances and then associate to the dtg with dtg.ItemsSource = obcCounters;

the result is enter image description here

which obviously is not showing the obcs in any way. So the question is: how can I in code behind show (in any way would do) those observable collections using code behind only? Thanks


Solution

  • You should transform each CfgCounters object into an item with only scalar properties, e.g.:

    ObservableCollection<CfgCounters> obcCounters = new ObservableCollection<CfgCounters>();
    ...
    dtg.ItemsSource = obcCounters.Select(x => new
    {
        x.valuePresent,
        x.Name,
        obcDatetime = string.Join(",", x.obcDatetime.Select(y => y.ToString("yyyy-MM-dd"))),
        obcLastExecutedPP = string.Join(",", x.obcLastExecutedPP),
        obcNumDimsOK = string.Join(",", x.obcNumDimsOK)
    }).ToArray();