2010-09-08 71 views
3

我不知道为什么我的代码没有正确执行TextWrapping。它不包装Description列的文本(这是我想要的)。它只是削减了它,它甚至不使用“...”让我知道有更多的数据。WPF DataGrid:如何将列设置为TextWrap?

我试图使用我在网上找到的代码来完成这项工作,但它没有奏效。理想情况下,我很想只能将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> 

在此先感谢!

回答

11

它不起作用,因为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 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> 
相关问题