Создать стиль для TextBlock в DataGridTextColumn - программирование

Создать стиль для TextBlock в DataGridTextColumn

Я хочу создать глобальный стиль, который устанавливает VerticalAlignment в Center для всех элементов TextBlock внутри DataGrid или внутри DataGridTextColumn.

Я не хочу копировать следующее в каждый DataGridTextColumn, потому что он чувствует себя повторяющимся.

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

Я пробовал что-то вроде следующего, но это не работает, потому что DataGridTextColumn не наследует от FrameworkElement или FrameworkContentElement. DataGrid сам, но любая последующая упаковка, которую я пытаюсь, приводит к ошибкам:

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

Ответ 1

Вы можете определить 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}". Таким образом, все ваши ячейки будут иметь контент с центром.

EDIT. Вышеприведенный код является одним из моих проектов, а также содержит код для удаления линий сетки в 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>

Ответ 2

Создать стиль как статический ресурс

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

Затем вы можете назначить его элементу ElementStyle в DataGridTextColumn

<DataGridTextColumn ElementStyle="{StaticResource verticalCenter}" />

Ответ 3

Просто используйте DataGridTemplateColumn:

<DataGridTemplateColumn Width="SizeToCells">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock HorizontalAlignment="Center" Width="100" Height="20"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>