14

我想创建一个全局样式,将a或 a内的所有控件设置VerticalAlignment为。CenterTextBlockDataGridDataGridTextColumn

我不想将以下内容复制到每个中DataGridTextColumn,因为它感觉重复。

<DataGridTextColumn Header="Some Property" Binding="{Binding SomeProperty}">
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="TextBlock">
            <Setter Property="VerticalAlignment" Value="Center"></Setter>
        </Style>
    </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

我尝试了类似以下的方法,但它不起作用,因为DataGridTextColumn它不继承自FrameworkElementor FrameworkContentElementDataGrid本身可以,但我尝试的任何进一步包装都会导致错误:

<Style TargetType="DataGridTextColumn">
    <Setter Property="ElementStyle">
        <Setter.Value>
            <Style TargetType="TextBlock">
                <Setter Property="VerticalAlignment" Value="Center"/>
            </Style>
        </Setter.Value>
    </Setter>
</Style>
4

3 回答 3

23

将样式创建为静态资源

<UserControl.Resources>
    <Style x:Key="verticalCenter" TargetType="{x:Type TextBlock}">
        <Setter Property="VerticalAlignment" Value="Center" />
    </Style>
</UserControl.Resources>

然后您可以将其分配给 DataGridTextColumn 的 ElementStyle

<DataGridTextColumn ElementStyle="{StaticResource verticalCenter}" />
于 2016-02-10T10:40:23.080 回答
13

您可以定义CellStyle如下:

<Style x:Key="DataGridCellStyle" TargetType="DataGridCell">
    <Setter Property="FocusVisualStyle" Value="{x:Null}" />
    <Setter Property="BorderThickness" Value="0"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

并将其分配给 DataGrid: CellStyle="{StaticResource DataGridCellStyle}"。这样,您的所有单元格都将以内容为中心。

编辑:上面的代码来自我的一个项目,还包含删除 DataGrid 中网格线的代码。您可以通过在模板中更改Grid为来取回它们。Border像这样:

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type DataGridCell}">
            <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>
于 2013-12-03T14:37:02.167 回答
2

只需使用DataGridTemplateColumn

<DataGridTemplateColumn Width="SizeToCells">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock HorizontalAlignment="Center" Width="100" Height="20"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
于 2014-08-05T20:47:19.547 回答