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?
If you consider your
ItemsSource, anObservableCollectionofObservableCollections, then you will recognize that the each row in the grid is just anObservableCollectionobject. TheDataGridis 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 theDataContextfor the row and use the public properties as columns (in this case, the only property ofObservableCollectionthat qualifies isCount)EDIT: I just remembered the
IBindingListinterface, which allows for a more complex binding scenario (I believe this is how theDataTablecan expose the columns as properties for binding purposes. Take a look at this answer for information onIBindingListand how it may prove useful. You may be able to create a custom class that derives fromObservableCollectionand implementsIBindingListto 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
DataTemplatefor the DataPoint type so that it knows how to visually display the type.