如何获得带有包装文本而不是截断文本的单元格的 WPF Datagrid?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4671836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How get a WPF Datagrid with cells that wrap text instead of truncating it?
提问by D.Rosado
What must be done to get a WPF DataGrid with cells that wrap text instead of truncating it?
必须做什么才能获得带有包装文本而不是截断文本的单元格的 WPF DataGrid?
Right now when a text is bigger and don't fit in a column the text is truncated and users can't see it value cos the DataGrid's IsReadOnly property is true. What I want is that the text in cells be wrapped and the cell height (NO CELL WIDTH) increased the amount needed to show all the text.
现在,当文本较大且不适合列中时,文本会被截断并且用户无法看到它的值,因为 DataGrid 的 IsReadOnly 属性为 true。我想要的是单元格中的文本被换行,并且单元格高度(无单元格宽度)增加了显示所有文本所需的数量。
采纳答案by H.B.
You could try to template the cells with a TextBlock
which has text-wrapping enabled.
您可以尝试使用TextBlock
启用了文本换行的a 对单元格进行模板化。
回答by D.Rosado
Thanks for your help @H.B., this did the trick for me (alignment is optional):
感谢您的帮助@HB,这对我有用(对齐是可选的):
<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>
回答by Rahbek
I made something similar to D.Rosados solution. Mine is however reusable if you have more columns that needs wrapping.
我做了一些类似于 D.Rosados 解决方案的东西。但是,如果您有更多需要包装的列,则我的可重复使用。
<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>
回答by sheraz yousaf
Another simple way of setting text wrap for Editing and Text DataGrid columns is to specity the Binding property and TextWrapping property as following:
为 Editing 和 Text DataGrid 列设置文本换行的另一种简单方法是指定 Binding 属性和 TextWrapping 属性,如下所示:
<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>