Binding a Column Header to Multiple DataGrid Headers
I came across this sample code on TechNet witch shows how to bind a single column header header and its corresponding column data:
<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>
<TextBlock Text="{Binding DataContext.HeaderNameText, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
and the DataContext DataGrid is set like this:
Data data = new Data();
data.HeaderNameText = "Header2";
data.Items = new List<string>() { "Item1", "Item2" };
DataContext = data;
The data class structure looks like this:
public class Data
{
public string HeaderNameText { get; set; }
public List<string> Items { get; set; }
}
my question is how to bind DataGrid ItemSource to multiple data columns:
List<Data> data=new List<Data>();
I am expecting to get a column for each data item in the above list, so how do I do this?
+3
source to share
1 answer
This approach defines only one column
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn ...>
</DataGrid.Columns>
</DataGrid>
For multiple columns, you will need to define it multiple times
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn ...>
<DataGridTemplateColumn ...>
<DataGridTemplateColumn ...>
</DataGrid.Columns>
</DataGrid>
If you define columns like this
public class Data
{
public string[] HeaderNameText { get; set; } // array, list, etc.
public List<string> Items { get; set; }
}
then the binding will be something like
{Binding DataContext.HeaderNameText[0] ...} {Binding DataContext.HeaderNameText[1] ...}
and etc.
+1
source to share