Tuesday, 28 August 2012

WPF Resizing Inner DataGrid Problem

I started this post in December last year and I am only just getting round to completing it now. While I was working a colleague came to me with a WPF problem which I had to look into and sort as it was bothering me.

The Problem:
A WPF DataGrid with each row having its own row details and the template for this is another DataGrid. This is fine however the tricky part was getting the inner DataGrid width to resize along with its columns when the window resizes like the outer grid will as long you are using the correct layout and no width has been set.

Now I have been doing WPF for about 3 years and I am still finding out the ins and outs of the DataGrid control I find it can be very powerful yet at the same time stab you in the back and not work the way you want, sometimes when problems like this arise they are extremely frustrating.

After looking into this somewhat the best option that I could come up with to do this without any code behind (XAML based only) was to bind the width of the inner grid to the ActualWidth property of its parent grid. for example:



<DataGrid Name="dgrDetails" DataContext="{Binding XPath=Tracks}" 
          ItemsSource="{Binding XPath=Track}" AutoGenerateColumns="False"
          Style="{StaticResource DataGridStyle}" Margin="0" 
          RowDetailsVisibilityMode="Collapsed"
          Width="{Binding ElementName=dgrMain, Path=ActualWidth}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="No." Binding="{Binding XPath=No}" Width="*" />
        <DataGridTextColumn Header="Title" Binding="{Binding XPath=Title}" Width="*" />
        <DataGridTextColumn Header="Length" Binding="{Binding XPath=Length}" 
                            Width="*" />
    </DataGrid.Columns>
</DataGrid>


I will upload the full source for this problem along with some other useful data grid examples up to my GitHub in the next 2 weeks and will link it in here.

No comments:

Post a Comment