I have an object called TestData that contains two properties, a string and an ObservableCollection. I have an ObservableCollection that I use to generate columns in a DataGrid in code. I have no problem dynamically generating the DataGridTextColumn and their respective headers based off of the TestData object, but I cannot bind the DataGridTextColumn Binding property to the ObservableCollection inside of TestData.
Now that I have stated the problem in words, let me clear it up by putting up the code:
TestData.cs
public class TestData
{
private ObservableCollection<string> data = new ObservableCollection<string>();
public string Header { get; set; }
public ObservableCollection<string> Data
{
get
{
return data;
}
set
{
data = value;
}
}
}
MainWindow.xaml.cs Code Behind
public partial class MainWindow : Window
{
private ViewModel viewModel = new ViewModel();
private List<string> headers = new List<string>();
private ObservableCollection<TestData> mainData = new ObservableCollection<TestData>();
public MainWindow(ViewModel vm)
{
InitializeComponent();
viewModel = vm;
this.DataContext = viewModel;
mainData = viewModel.MainData;
this.spreadSheet.ItemsSource = viewModel.MainData;
foreach (TestData data in mainData)
{
if (headers.Contains(data.Header) == false)
{
headers.Add(data.Header);
DataGridTextColumn col = new DataGridTextColumn();
int x = viewModel.MainData.IndexOf(data);
Binding bind = new Binding("Data");
bind.BindsDirectlyToSource = true;
bind.Source = mainData[x];
col.Binding = bind;
col.Header = data.Header;
this.spreadSheet.Columns.Add(col);
}
}
}
}
XAML MainWindow.xaml
<Grid>
<DataGrid AutoGenerateColumns="False" Height="Auto" HorizontalAlignment="Stretch" Name="spreadSheet" VerticalAlignment="Stretch" Width="Auto" />
</Grid>
If I place 4 TestData objects in my ObservableCollection I get their headers fine, but all of the data in the ObservableCollection inside the TestData objects just show as (Collection) in the DataGrid.
Thanks in advance!