Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize Datagrid Height after deselecting a RowDetailsTemplate

I am using RowDetailsTemplate to display a nested datagrid for a row. Now the datagrid expands in height when I select a row to show this nested datagrid. But it doesn't reduce its height when the row is deselected.

  1. Is there a way to resize the datagrid to its original height after the row details have been collapsed?

  2. Is it possible to do it declaratively?

like image 284
Pradeep Avatar asked Nov 05 '22 15:11

Pradeep


2 Answers

Place detail into StackPanel and grid with this this Behaviour:

public class DataGridDetailResizeBehavior : Behavior<FrameworkElement>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        this.AssociatedObject.SizeChanged += new SizeChangedEventHandler(Element_SizeChanged);
    }

    protected override void OnDetaching()
    {
        this.AssociatedObject.SizeChanged -= new SizeChangedEventHandler(Element_SizeChanged);
        base.OnDetaching();
    }

    private void Element_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        //Find DataGridDetailsPresenter
        DataGridDetailsPresenter rowDetailPresenter = null;
        var element = this.AssociatedObject;
        while (element != null)
        {
            rowDetailPresenter = element as DataGridDetailsPresenter;
            if (rowDetailPresenter != null)
            {
                break;
            }

            element = (FrameworkElement)VisualTreeHelper.GetParent(element);
        } 

        if (rowDetailPresenter != null)
        {
            var row = UIHelper.GetParentOf<DataGridRow>(this.AssociatedObject);
            if (row != null && row.DetailsVisibility == Visibility.Visible)
            {
                //Set height
                rowDetailPresenter.ContentHeight = this.AssociatedObject.ActualHeight;
            }
        }
    }
}

and XAML looks like this:

<sdk:DataGrid.RowDetailsTemplate>
    <DataTemplate>
        <StackPanel>
            <Grid>
                <sdk:DataGrid...

                <i:Interaction.Behaviors>
                    <myinteractivity:DataGridDetailResizeBehavior />
                </i:Interaction.Behaviors>
            </Grid>
        </StackPanel>
    </DataTemplate>
</sdk:DataGrid.RowDetailsTemplate>

This worked for me.

like image 156
HolaJan Avatar answered Nov 15 '22 06:11

HolaJan


Found a work around for this problem; on the selection changed event for the grid trigger a refresh of the grids items, this causes the grid to redraw itself.

    private void dgVehicles_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        DataGrid dg = sender as DataGrid;
        if (dg != null)
        {
            dg.Items.Refresh();
        }
        e.Handled = true;
    }

This worked for me. Hope it helps.

like image 28
RobD103 Avatar answered Nov 15 '22 05:11

RobD103