首页 > 解决方案 > 我可以让 DataGrid 样式的 Content Presenter 因列而异吗?

问题描述

我继承了以下样式:

<Style x:Key="MainPlanDataGridCell" TargetType="DataGridCell">
        <Setter Property="BorderThickness" Value="0" />
        <Setter Property="Height" Value="30" />
        <Setter Property="FrameworkElement.HorizontalAlignment" Value="Stretch" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridCell}">
                    <Grid Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Grid>
                    ...
    </Style>
    <Style x:Key="MainPlanTable" TargetType="{x:Type DataGrid}">
        ...
        <Setter Property="CellStyle" Value="{StaticResource MainPlanDataGridCell}" />
        ...
    </Style>

它在控件中使用如下:

<DataGrid
      Grid.Row="2"
      Grid.Column="0"
      ...
      Style="{StaticResource MainPlanTable}">
      <DataGrid.Columns>
                ...
      </DataGrid.Columns>
</DataGrid>

但我需要不同的单元格列有不同的对齐方式。有没有办法使用样式来实现这一点?如果没有,有人可以提出实现这一目标的最佳方法(高级方法)吗?

标签: wpfdatagridwpf-controls

解决方案


我为原型应用程序创建了类似的东西,如果可能的话,您可以提取样式。否则就这样使用它,

<DatGrid.Columns>
    <DataGridTemplateColumn Header="ColumnHeader1" Width="Auto">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding something}" //your alignment & other styles here />
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>

    <DataGridTemplateColumn Header="ColumnHeader2" Width="Auto">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBox Text="{Binding somethingElse}" //your alignment & other styles here />
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
...
</DataGrid.Columns>

您可以控制单元格是 TexBlock 还是 TextBox 或任何其他控件。也许为每个文本框/文本块制作一个样式并将其作为静态资源放在该 xaml 标记中。

注意:如果这样做,您需要设置<DataGrid AutoGenerateColumns="False">


推荐阅读