wpfstylescontentpresenter

Stretch the ContentPresenter in a DataGrid while keeping the Content in the middle?


I found that the easiest way to get my Content vertically and horizontally centered would be this:

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type DataGridCell}">
            <Grid Background="Gray">
                <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" />
            </Grid>
        </ControlTemplate>
    </Setter.Value>
</Setter>

But I don't really like that my actual TextBox doesn't fill the whole cell when trying to edit the cell value, but instead there is a white box around the value, which looks like this:

enter image description here

There is no way to set a HorizontalContentAlignment for the ContentPresenter and although I get the desired effect by using a TextBox in my ControlTemplate, like this:

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type DataGridCell}">
            <Grid VerticalAlignment="Stretch">
                <TextBox Text="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" BorderThickness="0" Background="Gray">
                </TextBox>
            </Grid>
        </ControlTemplate>
    </Setter.Value>
</Setter>

it requires a specific Binding to work, which defeats the whole purpose of re-usability.

What would be the best way to either have the white box stretch over the whole cell or disable the white box completely?


Solution

  • Instead of working with the ContentPresenter I found a way to bind Textbox to the Content, like this:

    <Style TargetType="DataGridCell" x:Key="TextBoxTemplateCellStyle" BasedOn="{StaticResource DefaultCellStyle}"> 
            <Setter Property="Width" Value="40" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Grid>
                            <TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" BorderThickness="0"  Background="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Background}">
                                <TextBox.Style>
                                    <Style TargetType="{x:Type TextBox}">
                                    </Style>
                                </TextBox.Style>
                            </TextBox>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    

    which allows me to stretch my textbox to the full with while not having the small, white box inside my gray Cell.