Labels

Tuesday, April 1, 2014

Word-wrapping text columns in DataGrid

image 
Just word-wrapping DataGridTextColumns in DataGrid sounds straightforward, but you have to use a few tricks…

<DataGrid ItemsSource="{Binding Source={StaticResource DataProvider}, XPath=transunit}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Width="Auto" Binding="{Binding XPath=@id}" Header="ID"/>
<DataGridTextColumn Width="*" Binding="{Binding XPath=source}" Header="Source">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Width="*" Binding="{Binding XPath=target}" Header="Target">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>

Add DataGridTextColumn.ElementStyle to the columns to be word-wrapped. Each Style and Setter child element needs to be configured as TargetType="TextBlock", Property="TextWrapping", and Value="Wrap". You also have to specify Width="*" or an explicit value in DataGridTextColumn so that the horizontal scrollbar will be disabled in DataGrid.


Link to source code: WordWrapTextColumnDemo

1 comment:

  1. Translation service provide Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our.

    ReplyDelete