Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set the initial state of a checkbox in WPF (either in XAML or code)?

I have two simple related controls on a form, a delete button and a confirm delete checkbox.

The idea is to protect against accidental deletions (don't worry, undo will be added later) but still allow the user to delete without annoying confirmations if they so wish.

However, I want the initial state of the checkbox to be set. The XAML code is currently:

<CheckBox Margin="0 5 0 0"
          x:Name="chkConfirmDel"
          Checked="chkConfirmDel_Change">
    Confirm delete?
</CheckBox>

but I can't see any obvious property for forcing the initial state, either in XAML or in the Window_Loaded() code.

like image 888
paxdiablo Avatar asked Jun 23 '10 03:06

paxdiablo


2 Answers

IsChecked="True"

like image 187
Quartermeister Avatar answered Oct 29 '22 11:10

Quartermeister


XAML:

<!-- Initialized checked -->
<CheckBox x:Name="cbxSwitch" IsChecked="True" Content="Simple switch" />

<!-- Initialized in third state -->
<CheckBox x:Name="cbxSwitch3" Content="3 state switch"
    IsThreeState="True" IsChecked="{x:Null}" />

CS:

// Two-state CheckBox doesn't require checking null
if (cbxSwitch.IsChecked == true)
{
    // Do something if selected
}

// In three-state CheckBox, IsChecked may be true, false or null
if (cbxSwitch3.IsChecked ?? false)
{
    // Do something only if IsChecked==true (selected)
}
like image 22
marbel82 Avatar answered Oct 29 '22 11:10

marbel82