Bind Complex Type in Silverlight Datagrid

1k Views Asked by At

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 silverlight? Right now it is displayes in Datagrid as "Namespace.EmployeeName" in each row.

2

There are 2 best solutions below

4
On BEST ANSWER

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>
0
On

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.