Search code examples
uwpcenteringuwp-xamlword-wrap

How to vertically center CheckBox graphic with respect to wrapping content


I have the following XAML structure

<StackPanel Orientation="Horizontal">

    <CheckBox>
        <TextBlock Text="Lorem ipsum dolor sit amet etc" TextWrapping="Wrap" Width="200"/>
    </CheckBox>

    <Button>
        <SymbolIcon Symbol="Delete"/>
    </Button>

</StackPanel>

Notice how the delete button and the text (strictly speaking the whole CheckBox) are vertically centred, but the actual graphic for the CheckBox is doing its own thing. This is because of the text wrapping - if it was a single line of text, it would all be centred.

enter image description here

How do I get the graphic to be vertically centred with the text (which is the contents of the CheckBox)?


Solution

  • I found the answer minutes later, from this question.

    1. Select the CheckBox in Document Outline in Visual Studio
    2. Right Click the CheckBox > Edit Template > Edit a Copy
    3. Locate the following code in ControlTemplate

      <Grid Height="32" VerticalAlignment="Top">
          <Rectangle x:Name="NormalRectangle" Fill="{ThemeResource CheckBoxCheckBackgroundFillUnchecked}" Height="20" StrokeThickness="{ThemeResource CheckBoxBorderThemeThickness}" Stroke="{ThemeResource CheckBoxCheckBackgroundStrokeUnchecked}" UseLayoutRounding="False" Width="20"/>
          <FontIcon x:Name="CheckGlyph" FontFamily="{ThemeResource SymbolThemeFontFamily}" Foreground="{ThemeResource CheckBoxCheckGlyphForegroundUnchecked}" FontSize="20" Glyph="&#xE001;" Opacity="0"/>
      </Grid>
      
    4. Change the VerticalAlignment property of the Grid from Top to Center.