简体   繁体   中英

Dynamic Datagrid Binding in Silverlight?

I should do binding for datagrid dynamically at code. I wrote the code as below. When I debug this code block, it seems that it does bindings correctly, but grid comes with no columns on form.

MyClass myInstance = new MyClass();
dataGridObject = new DataGrid();
dataGridObject.Width = 200;
dataGridObject.Height = 200;
binding = new Binding();
binding.Source = myInstance;
foreach (PropertyInfo prop in myInstance.GetType().GetProperties())
{
    binding.Path = new PropertyPath(prop.Name);
    DataGridTextColumn column = new DataGridTextColumn();
    column.Header = prop.Name;
    column.Binding = new Binding(prop.Name);
    dataGridObject.Columns.Add(column);
}

dataGridObject.ItemSource = myInstanceList;

Why doesn't come grid with columns, although I did necessary bindings? Thanks for the replies in advance..

In this case, why Don't you set the AutoGenerateColumns property of the Datagrid to true? When this property is set to True, the code you are writing is done for you.. All you have to do is bind the List of objects to the grid and the columns will be generated by the grid.

Your code should have worked. Did you add your DataGrid to the visual tree. eg

LayoutRoot.Children.Add(dataGridObject)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM