Madhav Joshi

Madhav Joshi

  • NA
  • 56
  • 18.4k

TreeView / Collapsible Datagrid Using Silverlight

Mar 4 2011 7:14 AM

Using RowDetailsTemplate might be useful to implement nested datagrids.

For example, your normal datagrid might look like this.

<data:DataGrid Name="ParentDG" AutoGenerateColumns="False" RowDetailsVisibilityMode="VisibleWhenSelected">
    <data:DataGrid.Columns>
        <data:DataGridTextColumn Header="<<ColumnInfo>>" Binding="{Binding <<BindingInfo>>}" IsReadOnly="True" />
        ... 
    </data:DataGrid.Columns>
    <data:DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <data:DataGrid Name="NestedDG"></data:DataGrid>
            </StackPanel>
        </DataTemplate>
    </data:DataGrid.RowDetailsTemplate>
</data:DataGrid>

Note that the RowDetailsVisibilityMode is set to "VisibleWhenSelected". Thus, whenever you click on a row in the datagrid, the content of rowdetailstemplate is displayed.

The only plumbing left now is to set the datasource of the inner-grid. You can do that by following these steps:
1. Create an event handler for "RowDetailsVisibilityChanged" event
    ParentDG.RowDetailsVisibilityChanged += new EventHandler<DataGridRowDetailsEventArgs>(ParentDG_RowDetailsVisibilityChanged);

2. Define the event handler to set the data-source for the inner-grid.
   void ParentDG_RowDetailsVisibilityChanged(object sender, DataGridRowDetailsEventArgs e)
     {
        DataGrid nestedGrid = (DataGrid)e.DetailsElement.FindName("NestedDG");
        if (e.Row.DetailsVisibility == Visibility.Visible)
        {
            nestedGrid.ItemsSource = <<Set the item source for the nested grid here>>;
        }
    }

Note that we obtian the nested grid from the DetailsElement and set the item source for the nested datagrid.


SOURCE : By implementation in my project and also Silverlight Official Forum


Answers (3)