How get a WPF Datagrid with cells that wrap text instead of truncating it?

冷暖自知 提交于 2019-11-30 01:44:28

You could try to template the cells with a TextBlock which has text-wrapping enabled.

Thanks for your help @H.B., this did the trick for me (alignment is optional):

<DataGrid.Columns>               
    <DataGridTextColumn Header="Wrapped & centered" Binding="{Binding field}">
        <DataGridTextColumn.ElementStyle>
             <Style>                            
                 <Setter Property="TextBlock.TextWrapping" Value="Wrap" />
                 <Setter Property="TextBlock.TextAlignment" Value="Center"/>
             </Style>
         </DataGridTextColumn.ElementStyle>
    </DataGridTextColumn>
</DataGrid.Columns>
Rahbek

I made something similar to D.Rosados solution. Mine is however reusable if you have more columns that needs wrapping.

<UserControl.Resources>
    <Style TargetType="{x:Type TextBlock}" x:Key="WrapText">
        <Setter Property="TextWrapping" Value="Wrap"/>
    </Style>
</UserControl.Resources>

<DataGrid.Columns>
    <DataGridTextColumn IsReadOnly="False" Header="Address" 
     Binding="{Binding Address}" ElementStyle="{StaticResource WrapText}" Width="150"/>
</DataGrid.Columns>

Another simple way of setting text wrap for Editing and Text DataGrid columns is to specity the Binding property and TextWrapping property as following:

<DataGridTemplateColumn x:Name="ColumnName" Header="Column Header Goes Here">
        <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                         <TextBox Text="{Binding Path=DataBoundProperty, Mode=TwoWay}" TextWrapping="Wrap"/>
                </DataTemplate>
        </DataGridTemplateColumn.CellEditingTemplate>
        <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=DataBoundProperty, Mode=OneWay}" TextWrapping="Wrap"/>
            </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!