Pages

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

WPF 4 Unleashed

My first and only WPF application so far is Bilingual Searcher, a freeware tool for reviewers and translators to batch-find and replace bilingual xml files. When I was working on this application, I just focused in on the completion of the project, so aside from the very basics of the data binding mechanism and MVVM pattern, I did not dig much deeper into the WPF architecture itself. But now that I have completed and released the application, I’ve decided to learn the various features of WPF again, from the usages of built-in controls and data binding to styles, templates, user controls, and custom controls.

Instead of googling at random each time I encounter a problem, it will no doubt be more beneficial to invest time in reading well-organized books. That’s why I’ve been reading WPF 4 Unleashed* for the last couple of days. This book covers a broad range of topics you need to know about WPF. Compiled into a book of over 800 pages long, it might be a little overwhelming for WPF beginners, but if you already have some experience in the development of WPF applications, it will not only serve as a useful reference to keep at hand but also deepen your understanding of the technology.

*This edition is actually a bit old and the next edition, WPF 4.5 Unleashed, is currently on the market.