首页 文章

WPF Datagrid单元格文本环绕

提问于
浏览
1

我有一个具有自定义样式的数据网格,因此我可以在整个应用程序中重用此格式 . 它有一个自定义列 Headers ,行样式等 . 我能够使文本包装在列 Headers 上工作,数据正确绑定到它 . 当我尝试在单元格上使用相同的技术时,绑定似乎不起作用但是换行 . 我已阅读以下帖子,但看起来我需要在每次放置数据网格后设置样式 . 它可以不在资源字典中完成,还是我在错误的位置应用包装?

wpf DataGrid change wrapping on cells

WPF toolkit datagrid cell text wrapping

WPF DataGrid Cell Text Wrapping - set to NoWrap (False)

这是datagrid定义(修剪):

<Style x:Key="EmbedDG" TargetType="{x:Type DataGrid}" >
    <Setter Property="ColumnHeaderStyle" Value="{DynamicResource DGCH}" />
    <Setter Property="CellStyle" Value="{DynamicResource EmbedDGCE}" />
</Style>

以下是显示文本换行的工作DGCH样式:

<Style x:Key="DGCH" TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock TextWrapping="Wrap" Text="{Binding}" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

这是不起作用的单元格样式(图1带有contenttemplate,2没有):

<Style x:Key="EmbedDGCE" TargetType="{x:Type DataGridCell}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock TextWrapping="Wrap" Text="{Binding}" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

Screenshot with the CellStyle ContentTemplate Applied

Screenshot without the CellStyle ContentTemplate Applied

编辑:

<DataGrid Style="{DynamicResource EmbedDG}" ItemsSource="{Binding Tags}" >
      <DataGrid.Columns>
          <DataGridTextColumn Header="Tag Type" Binding="{Binding TagType}" Width="180" />
          <DataGridTextColumn Header="Tag Comments" Binding="{Binding Message}" Width="300"/>
      </DataGrid.Columns>
</DataGrid>

1 回答

  • 3

    我将摆脱单元格样式并使用模板列 .

    <DataGrid Style="{DynamicResource EmbedDG}" ItemsSource="{Binding Tags}" >
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Tag Type" Width="180">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock 
                            Text="{Binding TagType}" 
                            TextWrapping="Wrap"
                            />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
    
            <DataGridTemplateColumn Header="Tag Comments" Width="300">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock 
                            Text="{Binding Message}" 
                            TextWrapping="Wrap"
                            />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
    

    我想它会给你完全限定的类名,因为你的单元格模板试图在TextBlock中显示一个对象 . 我没有时间玩它,但无论你的代码中有什么问题,上面都应该有效 .

相关问题