WPF 数据网格 : How do I set columns to TextWrap?

标签 wpf datagrid word-wrap

我不确定为什么我的代码没有正确执行 TextWrapping。它不会包装 Description 列的文本(这是我想要的)。它只是将其切断,甚至不使用“...”来让我知道有更多数据。

我尝试使用我在网上找到的这段代码来完成这项工作,但没有奏效。理想情况下,我希望能够只将 TextWrap 设置为某些列,而不是一般地跨所有 DataGridCell 对象。

哦,请注意,我使用的是 Microsoft.NET 4,所以这是通过它提供的 DataGrid,而不是来自 WPF Toolkit。

<DataGrid Name="TestGrid" Grid.Row="2" Grid.ColumnSpan="2" AutoGenerateColumns="False" ItemsSource="{Binding IntTypes}" SelectedValue="{Binding CurrentIntType}">
 <DataGrid.Resources>
  <Style TargetType="{x:Type DataGridCell}">
   <Setter Property="Template">
    <Setter.Value>
     <ControlTemplate TargetType="{x:Type DataGridCell}">
      <Border Name="DataGridCellBorder">
       <TextBlock Background="Transparent" TextWrapping="WrapWithOverflow" TextTrimming="CharacterEllipsis" Height="auto" Width="auto">
        <ContentPresenter Content="{TemplateBinding Property=ContentControl.Content}"  ContentTemplate="{TemplateBinding Property=ContentControl.Content}" />
       </TextBlock>
      </Border>
     </ControlTemplate>
    </Setter.Value>
   </Setter>
  </Style>
 </DataGrid.Resources>
 <DataGrid.Columns>
  <DataGridTextColumn Header="ID" Binding="{Binding ID}" IsReadOnly="True" />
  <DataGridTextColumn Header="Interested Parties Description" Binding="{Binding Description}" IsReadOnly="False"  />
 </DataGrid.Columns>
</DataGrid>

提前致谢!

最佳答案

它不起作用,因为您的 TextBlock 的“Text”属性实际上被设置为另一个对象,而不仅仅是一个字符串。在运行时,您的 VisualTree 看起来像:

Cell
  - TextBlock (w/ TextWrapping and TextTrimming)
    -  ContainerVisual
       -  ContentPresenter
          -  TextBlock (auto-generated by the DataGrid)

简而言之,您的代码基本上是在做这样的事情:
<TextBlock TextTrimming="CharacterEllipsis" TextWrapping="WrapWithOverflow">
  <TextBlock Text="The quick brown fox jumps over the lazy dog"/>
</TextBlock>

要解决此问题,请尝试按如下方式更新您的 ControlTemplate:
<ControlTemplate TargetType="{x:Type DataGridCell}">
    <Border Name="DataGridCellBorder">
        <ContentControl Content="{TemplateBinding Content}">
            <ContentControl.ContentTemplate>
                <DataTemplate>
                    <TextBlock Background="Transparent" TextWrapping="WrapWithOverflow" TextTrimming="CharacterEllipsis" 
                                Height="auto" Width="auto" Text="{Binding Text}"/>
                </DataTemplate>
            </ContentControl.ContentTemplate>
        </ContentControl>
    </Border>
</ControlTemplate>

关于WPF 数据网格 : How do I set columns to TextWrap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3671608/

相关文章:

c# - 多层应用程序中的依赖注入(inject)

.net - 使用 Style 在 WPF 中禁用列重新排序

.net - WPF XAML - 带有 ItemSource 和子菜单项的 MenuItem

WPF 文本框拦截 RoutedUICommands

javascript - ./src/App.js 模块未找到 : Can't resolve '@material-ui/data-grid' in xxx

c# - 基于 WPF 数据网格中的列值显示图像

wpf - 有没有人有在 MVVM 模式下工作的 WPF Datagrid 的代码示例?

java - 如何编写 java 库的 python 包装器

html - 如何阻止文本区域自动换行?

delphi - 将 SysUtils.WrapText() 与包含单引号的字符串一起使用