Monday, May 23, 2011

Wrap Text in Silverlight Datagrid Columns

The old code shows how the text column was bound to a Key-Value pair. But the problem was if the value is larger, then it will exceed the 190 pixels width.

To resolve the problem, I have to use a "CellTemplate" and "DataTemplate" as shown in the new code. The "TextWrapping" element is the key.

Happy Coding.



OLD CODE:
<data:DataGrid.Columns>
<data:DataGridTextColumn Binding="{Binding Path=Key}" FontWeight="Bold" Width="120" />
<data:DataGridTextColumn Binding="{Binding Path=Value}" Width="190" />
</data:DataGrid.Columns>

NEW CODE:
<data:DataGrid.Columns>
<data:DataGridTemplateColumn>
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Key}" FontWeight="Bold" Width="118" TextWrapping="Wrap" Margin="2,2,2,2" ></TextBlock>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
<data:DataGridTemplateColumn>
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Value}" FontWeight="Normal" Width="188" TextWrapping="Wrap" Margin="2,2,2,2" ></TextBlock>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
</data:DataGrid.Columns>

All Blogs so far ...