views:

40

answers:

1

I'm not sure why my code isn't doing the TextWrapping properly. It doesn't wrap the text for the Description column (which is what I want). It just cuts it off and it doesn't even use the "..." to let me know there is more data.

I tried to use this code I found online to do the job, but it didn't work. Ideally I'd love to be able to only set TextWrap to certain columns and not generically across all DataGridCell objects.

Oh, and please do note that I am using Microsoft.NET 4 so this is the DataGrid offered through that, not from the 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>

Thanks in advanced!

+1  A: 

It Doesn't work because the "Text" property of your TextBlock is actually being set to another object instead of just a string. At runtime, your VisualTree looks something like:

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

In short, you're code is essentially doing something like this:

<TextBlock TextTrimming="CharacterEllipsis" TextWrapping="WrapWithOverflow">
  <TextBlock Text="The quick brown fox jumps over the lazy dog"/>
</TextBlock>

To fix this, try updating your ControlTemplate as follows:

<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>
karmicpuppet