I want to bind a collection of objects to a DataGrid in Silverlight. The objects belong to the following type:
public class Seats
{
Dictionary<Group, long> dctValues = new Dictionary<Group, long>();
public int Id { get; set; }
public Dictionary<Group, long> Values
{
get { return dctValues; }
}
}
Whereas, Group is represented by:
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
}
I want to be able to generate columns based on the dictionary of groups, where each column would have the header set to Group.Name and the cell value for each item equal to the long value in the dictionary.
I’m going to assume that we can’t guarantee that there is only a single instance of a
Groupclass for each group name. (Else you would be generating columns based on a list of known groups no?)Here is a class derived from
DataGrid:Place an instance of this class in Xaml and assign a
List<Seats>to itsSeatsListproperty and it generates the columns and renders the rows.How does it work?
The magic starts in the
OnSeatsListPropertyChangedmethod. It first gets a list of distinct Group names. It generates a new Text column for each group name setting the header naturally to the group name.The weird stuff appears when setting the binding for the column. The binding is given a converter which for convience I decided to implement on the
SeatsGridclass as well. The converter parameter is the group name. Since no path is specified the wholeSeatsobject will be passed to the converter when binding actually occurs.Now looking at the
IValueConverter.Convertmethod. It finds an instance (is any) ofGroupin the seats that has the same name as the converter parameter. If found uses thatGroupas the key to lookup a value to return.If the Groups were known to be unique per name then the code can be simplified but the principle is the same.