How can I align a CheckBox with its content?
I know it's too late, but here is a better solution, without setting margins. Margins should be set differently for different heights of TextBlock
or Checkbox
.
<CheckBox VerticalAlignment="Center" VerticalContentAlignment="Center">
<TextBlock Text="Well aligned Checkbox" VerticalAlignment="Center" />
</CheckBox>
Update:
It's worth checking out @nmarler's comment below.
Edit - New Answer: (previous was no good)
Not the best way i believe , but can do the work:
<CheckBox>
<TextBlock Text="Poorly aligned CheckBox" Margin="0,-2,0,0"/>
</CheckBox>
Using negative margin to push the content up, result:
The default Style of a CheckBox
don't look like that in WPF. It aligns perfectly in both XP and Windows 7. Can you give a better description of how to reproduce this problem?
Two things I can think of to get the offset that you're seeing is either changing the Padding
or the VerticalContentAlignment
. The default CheckBox
value for VerticalContentAlignment
is Top
and a CheckBox
with Content
has Padding
set to "4,0,0,0"
. Try to change these two around and see if it makes any difference.
Here is a comparison
From the following Xaml
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<CheckBox Grid.Row="0"
Content="Poorly aligned CheckBox" Margin="9" />
<CheckBox Grid.Row="1"
Content="Padding=4,4,0,0" Margin="9" Padding="4,4,0,0"/>
<CheckBox Grid.Row="2"
Content="Vertical Center" Margin="9"
VerticalContentAlignment="Center"/>
<CheckBox Grid.Row="3"
Content="Vertical Top" Margin="9"
VerticalContentAlignment="Top"/>
</Grid>
There is a simple solution for this without needing to make a text block for the content, and without writing extra code that you don't need. Just use "VerticalContentAlignment". Example:
<CheckBox Content="Sample of Text" VerticalContentAlignment="Center"/>