简体   繁体   English

Silverlight中的动态Datagrid绑定?

[英]Dynamic Datagrid Binding in Silverlight?

I should do binding for datagrid dynamically at code. 我应该在代码中动态绑定datagrid。 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? 在这种情况下,为什么不将Datagrid的AutoGenerateColumns属性设置为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. 当此属性设置为True时,将为您完成编写的代码。您要做的就是将对象列表绑定到网格,并且这些列将由网格生成。

Your code should have worked. 您的代码应该可以正常工作。 Did you add your DataGrid to the visual tree. 您是否已将DataGrid添加到可视树。 eg 例如

LayoutRoot.Children.Add(dataGridObject)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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