WPF DataGrid, Help with Binding to a List<X> where each X has a Dictionary<Y,object> property.
Posted
by panamack
on Stack Overflow
See other posts from Stack Overflow
or by panamack
Published on 2010-04-06T16:49:40Z
Indexed on
2010/04/06
16:53 UTC
Read the original article
Hit count: 241
wpf
|wpftoolkit
I'm building an application which helps someone manage an event and works with data originating from Excel.
I want to use the WPF Toolkit DataGrid to display the incoming data but can't guarantee how many Columns there are going to be or what information they will contain.
I'd like to have an Info class that stores column information and have each Visitor at my Event own a Dictionary that uses shared references to Info objects for the keys.
Here's the general gist:
public class Info{
public string Name{get;set;}
public int InfoType{get;set;}
}
public class Visitor{
public Dictionary<Info,object> VisitorInfo {get;set;}
}
public class Event{
public List<Visitor> Visitors{get;set;}
public Event(){
Info i1 = new Info(){ Name = "ID", InfoType = 0};// type 0 for an id
Info i2 = new Info(){ Name = "Name", InfoType = 1};// type 1 for a string
Info i3 = new Info(){ Name = "City", InfoType = 1};
Visitor v1 = new Visitor();
v1.VisitorInfo.Add(i1, 0);
v1.VisitorInfo.Add(i2, "Foo Harris");
v1.VisitorInfo.Add(i3, "Barsville");
Visitor v2 = new Visitor();
...
this.Visitors.Add(v1);
this.Visitors.Add(v2);
...
}
}
XAML:
<!-- Window1.xaml -->
...
<local:Event x:Key="MyEvent"/>
...
<wpftk:DataGrid
DataContext="{StaticResource MyEvent}"
ItemsSource="{Binding Path=Visitors}" />
Disappointingly, DataGrid just sees a collection of Visitors each having a VisitorInfo property and displays one column called VisitorInfo with the string "(Collection)" once for each Visitor.
As a workaround I've created a ListTVisitorToDataTableConverter that maps Infos to DataColumns and Visitors to DataRows and used it like this:
<wpftk:DataGrid
DataContext="{StaticResource Event}"
ItemsSource{Binding Path=Visitors,
Converter={StaticResource MySmellyListTVisitorToDataTableConverter}}" />
I don't think this is good though, I haven't started trying to convert back yet which I guess I'll need to do if I want to be able to edit any data!
How can I do better?
Thanks.
© Stack Overflow or respective owner