Bind Complex Type in Silverlight Datagrid
I have created a Complex Type called "EmployeeName" using the Entity Framework designer in VS 2010. EmployeeName consists of FirstName,LastName & title. Now question is how do i display/bind to datagrid in s开发者_如何学运维ilverlight? Right now it is displayes in Datagrid as "Namespace.EmployeeName" in each row.
Firstly you need to set AutoGenerateColumns to false on the DataGrid to avoid getting the default column type of DataGridTextColumn for all the properties of your bound objects.
You then need to define the columns in xaml for each of the properties of your bound objects that you want displayed. For properties with a simple type like string
or int
(for example) you can just use a DataGridTextColumn
with a standard binding in the binding property.
For your complex type (EmployeeName
) you need to use a DataGridTemplateColumn
, and then define a DataTemplate
for the DataGridTemplateColumn.CellTemplate
property which tells the column how to display an EmployeeName
. A simple example which just uses a single TextBlock
and a Run
for each property of the EmployeeName
would be as follows
<sdk:DataGrid ItemsSource="{Binding MyCollection}"
AutoGenerateColumns="false">
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn>
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding EmployeeName.Title}"></Run>
<Run Text="{Binding EmployeeName.FirstName}"></Run>
<Run Text="{Binding EmployeeName.LastName}"></Run>
</TextBlock>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
You have to create each column in XAML and set AutoGenerateColumns to false, as well as binding each column manually to the property you want to display using the Binding property of each column.
http://www.wpftutorial.net/DataGrid.html
That site has more info in the subject. It is designed for WPF but it will work for Silverlight as well ;)
Good Luck and Enjoy programming.
精彩评论