I have WPF datagrid. I want to use
i) maximum available width for "Description" textblock (present inside 1st column)
ii) Auto width for Image control (present inside 1st column) and
iii) "Auto" width for rest of the column.
I have written follwing xaml code. But width is not working as per requriement.
Edit Issue : Instead, 2nd column text is getting truncated.
screenshot:
Any suggestions? Thanks!
<Grid Margin="10,0,10,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<DataGrid Grid.Row="0" Grid.ColumnSpan="2" ItemsSource="{Binding SelectedItemsCollectionView}" HorizontalAlignment="Stretch" AutoGenerateColumns="False">
<DataGrid.Columns>
<!--Get maixmum available space for 1st Column-->
<DataGridTemplateColumn Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid Margin="5,0,0,0">
<Grid.ColumnDefinitions>
<!--Get "Auto" space for Image control-->
<ColumnDefinition Width="Auto" />
<!--Get remaining available space for Description textblock-->
<ColumnDefinition Width="*" ></ColumnDefinition>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Stretch="None" Margin="0,0,5,0" Source="{Binding Converter={StaticResource ShowHideToImageConverterRef}, Path=IsHidden}"
Visibility="{Binding Converter={StaticResource VisibilityConverterRef}, Path=RowType}" HorizontalAlignment="Center"/>
<TextBlock Grid.Column="1" Text="{Binding Description}" VerticalAlignment="Center" HorizontalAlignment="Left" />
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!--Get "Auto" space for 2nd Column-->
<DataGridTextColumn Binding="{Binding Comments}" Width="Auto" />
</DataGrid.Columns>
</DataGrid>
<Label Grid.Row="1" Grid.Column="0" Content="Name" ></Label>
<TextBox Grid.Row="1" Grid.Column="1" Margin="10,0,0,0" Text="{Binding EmpName}"/>
</Grid>
Issue resolved after applying below solution suggested by Scott on other stackoverflow post "DataGrid column width doesn't auto-update".
1) In your DataGridTextColumn Bindings (all except your * sized column) set NotifyTargetUpdated=True.
2) On your DataGrid, add a handler to the TargetUpdated event.
3) In your TargetUpdated event handler:
-- a) Set the DataGrid's * sized column's width to 0.
-- b) Call the UpdateLayout() method on the DataGrid.
-- c) Set the DataGrid's * sized column's width back to new DataGridLength(1, DataGridLengthUnitType.Star)