legacybass
legacybass

Reputation: 592

Bind a datagrid one object per cell

I would like to bind some objects to a datagrid in WPF. I would VERY MUCH like to avoid DataTable!

Consider the following code:

public ObservableCollection<ObservableCollection<DataPoint>> GridItems { get; set; }

public class DataPoint : INotifyPropertyChanged
{
    public float Value { get; set; }
    public float OriginalValue { get; set; }
    public bool Highlighted { get; set; }
    public SolidColorBrush HighlightColor { get; set; }
    ...
}

XAML:

<toolkit:DataGrid ItemsSource="{Binding GridItems}" />

When we bind this to a DataGrid instead of getting one DataPoint object per cell we get one column with Count as the property shown. I have tried 2D arrays, custom types (inheriting from ObservableCollection<DataPoint>), HierarchicalDataTemplate but nothing seems to be working.

I do not know before-hand how many columns there are going to be, but it will always be the same number and type for every row. Any suggestions?

Upvotes: 3

Views: 835

Answers (1)

Brian S
Brian S

Reputation: 5785

If you consider your ItemsSource, an ObservableCollection of ObservableCollections, then you will recognize that the each row in the grid is just an ObservableCollection object. The DataGrid is not smart enough to look inside of the collection at each item (and it doesn't make sense - there might be a different number of items in each collection, so it can't automatically map the items to columns). It will just look at the object that is the DataContext for the row and use the public properties as columns (in this case, the only property of ObservableCollection that qualifies is Count)

EDIT: I just remembered the IBindingList interface, which allows for a more complex binding scenario (I believe this is how the DataTable can expose the columns as properties for binding purposes. Take a look at this answer for information on IBindingList and how it may prove useful. You may be able to create a custom class that derives from ObservableCollection and implements IBindingList to expose the DataPoints as properties.

original:

Since you don't know how many columns there will be, you can't declaratively databind them through XAML. I believe you're going to need to manually create the columns in code and set the Binding for each column.

Also, you'll need a DataTemplate for the DataPoint type so that it knows how to visually display the type.

Upvotes: 2

Related Questions