I’m currently tasked with building a spreadsheet-like GUI for a WPF application and I’ve run into some issues. Essentially, I want to bind to a datagrid on a column basis so that one column contains data for a certain year. So given that 2006 is the start year and 2009 the end year, I would like to have 4 columns each displaying values for a given year on a column basis.
This is what I have in the code-behind right now:
private Years m_YearsList;
public Years YearsList
{
get { return m_YearsList; }
set { m_YearsList = value; }
}
public MainWindow()
{
InitializeComponent();
YearsList = LoadData();
TestGrid.DataContext = YearsList;
}
public Years LoadData()
{
var personer = new Years{
new Year
{
Taxed = new Taxed {TaxedField = 10},
NumBuildings = new BuildingsCollection {NumBuildings = 25},
Area = new Area{AreaField = "NoWhere"},
DisplayName = "Person1"
},
new Year
{
Taxed = new Taxed{TaxedField = 2},
NumBuildings = new BuildingsCollection{NumBuildings = 8},
Area = new Area{AreaField = "SomeWhere"},
DisplayName = "Person2"
},
new Year
{
Taxed = new Taxed{TaxedField = 18},
NumBuildings = new BuildingsCollection{NumBuildings = 20},
Area = new Area{AreaField = "UpThere"},
DisplayName = "Person3"
}
};
return personer;
}
}
The Year object simply wraps two int’s and a string. The Years object is a desperation shot from me looking like this:
public class Years : List<Year>{}
My XAML:
<DataGrid x:Name="TestGrid" ItemsSource="{Binding}" CanUserAddRows="False" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=NumBuildings}" />
<DataGridTextColumn Binding="{Binding Path=Taxed}" />
<DataGridTextColumn Binding="{Binding Path=Area}" />
</DataGrid.Columns>
</DataGrid>
This code generates this:

As you can see, the Year objects are bound to one property per column while I would essentially like to have them bound to one object with all properties in a single column. Unfortunately my WPF skills are lacking here. 🙁
I found this article which talks about creating a datatable and transposing it (i.e. swapping the rows for columns) and then binding that object to the datagrid. So write a method that creates a transposed datatable from your collection and bind this table to the datagrid.
The problem is that this won’t really update, so if your data is supposed to be edited by the user in the datagrid, then you kinda have a problem.
You can either change your datasource directly, or you might have to edit the ControlTemplate of the datagrid.