SilverLight DataGrid Binding
I was working on the unbound SilverLight DataGrid and thought to write one in this regard,
There are scenarios when you don't have a predefined collection of objects to bind to SilverLight DataGrid or you don't know the structure of the object to bind with untill run time. For Example you want to bind the DataGrid with XML or to any other source.
So the way is to Create the Structure (Type/Class) of object dynamically on the fly and then build the generic List of newly created Type and bind it to SilverLight DataGrid. Moreover you want to add the new empty rows in grid, get the object bound to that row, Extract the values from the bound object, delete a row etc......
Lets first look at how to create a new Type(class) on the fly with properties and bind it to the DataGrid;
Dynamic Typed Objects Creation by Vladimir Bodurov (thanks)
Update the DataSourceCreator class to add a public property to maintain the type of the new structure
public static Type getType{get; set;}
and set this property before the last return statement of the ToDataSource function
getType = tb.CreateType();
Now how to get the bound Object of selected row of DataGrid on a button click & get values of the properties
var item = Activator.CreateInstance(DataSourceCreator.getType);
int index = mygrid.SelectedIndex;
item = mygrid.SelectedItems[0];
MethodInfo theMethod = DataSourceCreator.getType.GetMethod("get_Column1");
object res = theMethod.Invoke(item, new object[0]);
in the above code i created the new var variable of the Type and stores the selected bound object in it. And then using reflection extracted the value of the property Column1.
Lets Add new row in SilverLight DataGrid
IEnumerable<object> collection = mygrid.ItemsSource.Cast<object>();
List<object> list = collection.ToList();
var item = Activator.CreateInstance(DataSourceCreator.getType);
list.Add(item);
mygrid.ItemsSource = list;
It first gets the bound collection of the DataGrid and then adds a new object into the collection
Similarly you can remove an object from the bound collection
list.Remove(item)
Its all about Unbound Simulation of SilverLight DataGrid. Cheers :)