是否可以让 DataGrid 样式的内容演示器因列而异?



我继承了以下样式:

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

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

如果使用具有内置列类型(如DataGridTextColumn(的DataGrid并希望更改对齐方式,则无需更改控制模板,只需创建一个样式并将其设置为列的ElementStyle即可。

<!-- Example style that centers the text block in the column -->
<Style x:Key="TextBlockColumnAlignCenterStyle"
TargetType="{x:Type TextBlock}"
BasedOn="{StaticResource {x:Type TextBlock}}">
<Setter Property="TextAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>

TargetType必须与列中的控件匹配。这是DataGridCheckBoxColumn的一个示例。

<Style x:Key="CheckBoxColumnAlignCenterStyle"
TargetType="{x:Type CheckBox}"
BasedOn="{StaticResource {x:Type CheckBox}}">
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>

要应用这些样式,只需将它们分配给DataGrid中的目标列,例如:

<DataGrid ItemsSource="{Binding MyItems}" AutoGenerateColumns="False">
<!-- ...other code. -->
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding MyText}"
ElementStyle="{StaticResource TextBlockColumnAlignCenterStyle}"/>
<DataGridCheckBoxColumn Binding="{Binding MyBoolean}"
ElementStyle="{StaticResource CheckBoxColumnBackgroundStyle}"/>
</DataGrid.Columns>
</DataGrid>

请注意,ElementStyle仅适用于数据网格单元格的非编辑模式。如果需要在编辑模式下更改路线或其他特性,也必须为EditingElementStyle创建样式。

如果您需要在列中具有自定义控件,则可以使用DataGridTemplateColumn并创建自定义DataTemplate,但对于文本等简单数据,这是不必要的,请使用内置列。

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

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

最新更新