Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf checkbox selected when clicked outside of label

Tags:

checkbox

wpf

It seems my checkbox width is stretching to the extents of grid cell in which it is contained. So if you check way to the right of the checkbox label it still toggles the value. Is there a way to make the checkbox only toggle when the label or checkbox is clicked without hardcoding a width value for the checkbox?

like image 639
tim Avatar asked Dec 05 '10 18:12

tim


3 Answers

If you set your column definition width to "Auto" then the column will be resized to fit the CheckBox.

However, that might ruin your layout.

An alternative is to wrap the CheckBox in a StackPanel.

    <Grid Margin="10,10,10,10" Name="grid1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="Hello"/>
        <StackPanel Grid.Column="1" Orientation="Horizontal">
            <CheckBox Content="Click Me"/>
        </StackPanel>
        <Button Grid.Column="2" Content="Press Me"/>
    </Grid>

As you can see from the first screen shot, the bounding box of the CheckBox is now just around the check and label as opposed to being the full width of the column as shown by the second.

Correct behaviour:
correct behaviour
Incorrect behaviour:
incorrect behaviour

like image 64
ChrisF Avatar answered Nov 10 '22 00:11

ChrisF


The default HorizontalAlignment of CheckBox is Stretch. Try setting it to Left/Right/Center.

like image 43
krishnaaditya Avatar answered Nov 09 '22 23:11

krishnaaditya


It may really stretch that wide. Try to apply some background to the CheckBox - this will show you how wide it is in reality. Also play with HorizontalAlignment.

like image 3
TarasB Avatar answered Nov 09 '22 22:11

TarasB