2010-09-08 74 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> 
相關問題