Search code examples
silverlightdatagridrowdetails

Silverlight DataGrid: Can't seem to get the RowDetailsVisibilityChanged to fire on load of the grid?


I have a standard Silverlight DataGrid with the RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.VisibleWhenSelected

I tried setting this property both in the XAML as well as in the parent control's Loaded event. In the parent's Loaded event I'm setting the itemsource of the grid, then manually setting the selected index to 0. This does NOT fire the RowDetailsVisibilityChanged event.

However, once I change the selection by clicking a new row, it will fire. I need to access that first selection's row's "DetailElement" to populate a control within it with data. However the only way I know how to get that DetailElement is in the RowDetailsVisibilityChanged event.

Here's my code:

void ViewAssociationUserControl_Loaded(object sender, RoutedEventArgs e)
    {
        viewAssociationsDataGrid.RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.VisibleWhenSelected;
        viewAssociationsDataGrid.ItemSource = myData;
        viewAssociationsDataGrid.SelectedIndex = 0;
    }

private void viewAssociationsDataGrid_RowDetailsVisibilityChanged(object sender, System.Windows.Controls.DataGridRowDetailsEventArgs e)
    {
        if (viewAssociationsDataGrid.RowDetailsVisibilityMode == DataGridRowDetailsVisibilityMode.VisibleWhenSelected
            && e.Row.DetailsVisibility == System.Windows.Visibility.Visible)
        {
            Grid detailElement = e.DetailsElement as Grid;
            if (detailElement != null)
            {
                ListBox assocControl = detailElement.FindName("oneToManyGridPanel") as ListBox;
                UpdateOneToManyPanel(assocControl);
            }
        }
    }

Solution

  • I couldn't figure out a way to cleanly handle this scenario so I ended up hi-jacking the initial "selection changed" occurrence and that first time, manually fire the visibility changed event myself:

    private void viewAssociationsDataGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (!initialTriggerFired) //manually fire the visibility the first time
            {
                initialTriggerFired = true;
                DataGrid dataGrid = sender as DataGrid;
    
                int selectedIndex = dataGrid.SelectedIndex;
                if (selectedIndex > -1)
                {
                    DataGridColumn column = dataGrid.Columns[0];
                    FrameworkElement fe = column.GetCellContent(dataGrid.SelectedItem);
                    DataGridRow row = fe.GetAncestorOfType<DataGridRow>();
    
                    if (row != null)
                    {
                        row.DetailsVisibility = System.Windows.Visibility.Collapsed;
                        row.DetailsVisibility = System.Windows.Visibility.Visible;
                    }
                }
            }
        }