Reputation: 480
I have this XAML code:
<Window>
<Grid Name="gridBase" Width="Auto" Height="Auto">
<DataGrid Grid.Row="1" DataContext="{StaticResource ItemCollectionViewSource}" ItemsSource="{Binding}" AutoGenerateColumns="False" CanUserAddRows="False" Name="dgPatchContent" Margin="10, 20, 10, 10" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding SoftwareName}" Header="Software Name" />
<DataGridCheckBoxColumn Binding="{Binding AssignmentStatus_Stopped, UpdateSourceTrigger=PropertyChanged}" Header="Stopped" MinWidth="55" CanUserResize="False" />
<DataGridCheckBoxColumn Binding="{Binding AssignmentStatus_New, UpdateSourceTrigger=PropertyChanged}" Header="New" MinWidth="55" CanUserResize="False" />
<DataGridCheckBoxColumn Binding="{Binding AssignmentStatus_Pilot, UpdateSourceTrigger=PropertyChanged}" Header="Pilot" MinWidth="55" CanUserResize="False" />
<DataGridCheckBoxColumn Binding="{Binding AssignmentStatus_Productive, UpdateSourceTrigger=PropertyChanged}" Header="Prod" MinWidth="55" CanUserResize="False" />
</DataGrid.Columns>
</DataGrid>
<StackPanel HorizontalAlignment="Right" VerticalAlignment="Bottom" Grid.Row="2" Orientation="Horizontal">
<Button Content="OK" MinWidth="80" Margin="10,10,10,10" />
<Button Content="Cancel" MinWidth="80" Margin="0,10,10,10" />
</StackPanel>
</Grid>
</Window>
The DataGrid is filled with objects containing some dummy values for testing purposes. The first few entries in the SoftwareName column have rather short strings (~10 characters). At the bottom I've added a large string (~60 characters).
I want to have the Cells have the Width of the largest string in that column when the application launches. Currently when I start it, the Width is the size of the largest string which is visible in my DataGrid
. Only when I scroll to the bottom the DataGrid
and Window resizes to the Width of the large 60char string.
I've played around with Width="SizeToContent"
or "SizeToCells
" but nothing seems to make the DataGrid
have the correct size after the application has launched. Can someone point me in the right direction please?
Thanks for any help!
Upvotes: 3
Views: 5353
Reputation: 4774
Well, DataGrid
has row virtualization enabled by default, so only visible row objects are created initially, and the grid itself knows only about currently visible cells sizes:
When the EnableRowVirtualization property is set to true, the DataGrid does not instantiate a DataGridRow object for each data item in the bound data source. Instead, the DataGrid creates DataGridRow objects only when they are needed...
If your DataGrid
is not a big one, then a most simple solution will be just to set EnableRowVirtualization="False"
, then the sizing will work from the start.
Upvotes: 4