核取方塊Check boxes

核取方塊可用於選取或取消選取動作項目。A check box is used to select or deselect action items. 它可以用於單一項目或使用者可從中選擇的多個項目清單。It can be used for a single item or for a list of multiple items that a user can choose from. 這個控制項有三個選項狀態:未選取、已選取,以及不確定。The control has three selection states: unselected, selected, and indeterminate. 當子選項集合同時含有未選取和已選取狀態時,請使用不確定狀態。Use the indeterminate state when a collection of sub-choices have both unselected and selected states.

核取方塊狀態範例

取得 Windows UI 程式庫Get the Windows UI Library

WinUI 標誌

Windows UI 程式庫 2.2 或更新版本中有這個控制項使用圓角的新範本。Windows UI Library 2.2 or later includes a new template for this control that uses rounded corners. 如需詳細資訊,請參閱圓角半徑For more info, see Corner radius. WinUI 是 NuGet 套件,其中包含適用於 Windows 應用程式的新控制項和 UI 功能。WinUI is a NuGet package that contains new controls and UI features for Windows apps. 如需詳細資訊 (包括安裝指示),請參閱 Windows UI 程式庫For more info, including installation instructions, see Windows UI Library.

平台 API: 類別Checked 事件IsChecked 屬性Platform APIs: CheckBox class, Checked event, IsChecked property

這是正確的控制項嗎?Is this the right control?

針對二元 (是/否) 選項 (例如用於 [記住我?]) 使用 單一核取方塊Use a single check box for a binary yes/no choice, such as with a "Remember me?" 登入案例或是用於服務合約條款。login scenario or with a terms of service agreement.

針對個別選項使用單一核取方塊

對於二元選項, 核取方塊切換開關之間的主要差異為核取方塊適用於狀態,而切換開關適用於動作。For a binary choice, the main difference between a check box and a toggle switch is that the check box is for status and the toggle switch is for action. 您可以延遲認可核取方塊互動 (例如,作為表格提交的一部分),此時應該立即認可切換開關互動。You can delay committing a check box interaction (as part of a form submit, for example), while you should immediately commit a toggle switch interaction. 此外,多個選項僅允許使用核取方塊。Also, only check boxes allow for multi-selection.

針對使用者從不會互斥的選項群組中,選擇一個或多個項目的複選案例,請使用 多個核取方塊Use multiple check boxes for multi-select scenarios in which a user chooses one or more items from a group of choices that are not mutually exclusive.

當使用者可以選取任何選項組合時,建立核取方塊群組。Create a group of check boxes when users can select any combination of options.

使用核取方塊選取多個選項

將選項分組時,您可以使用不確定的核取方塊來代表整個群組。When options can be grouped, you can use an indeterminate check box to represent the whole group. 當使用者選取群組中部分而非全部的子項目時,請使用核取方塊的不確定狀態。Use the check box's indeterminate state when a user selects some, but not all, sub-items in the group.

用來顯示混合選項的核取方塊

核取方塊選項按鈕 控制項都能讓使用者從選項清單中選取。Both check box and radio button controls let the user select from a list of options. 核取方塊可讓使用者選取一個選項組合。Check boxes let the user select a combination of options. 相反地,選項按鈕可讓使用者從互斥的選項中進行單一選擇。In contrast, radio buttons let the user make a single choice from mutually exclusive options. 當有一個以上選項但僅能選取一個時,請改用選項按鈕。When there is more than one option but only one can be selected, use a radio button instead.

範例Examples

XAML controls gallery

如果您已安裝 XAML 控制項庫應用程式,請按一下這裡開啟應用程式並查看 CheckBox 運作情形If you have the XAML Controls Gallery app installed, click here to open the app and see the CheckBox in action.

建立核取方塊Create a checkbox

若要對核取方塊指派標籤,請使用 Content 屬性。To assign a label to the checkbox, set the Content property. 標籤會顯示在核取方塊旁邊。The label displays next to the checkbox.

這個 XAML 會建立單一核取方塊,以便在可提交表單之前用來同意服務條款。This XAML creates a single check box that is used to agree to terms of service before a form can be submitted.

<CheckBox x:Name="termsOfServiceCheckBox" 
          Content="I agree to the terms of service."/>

以下是使用程式碼建立的同一個核取方塊。Here's the same check box created in code.

CheckBox checkBox1 = new CheckBox();
checkBox1.Content = "I agree to the terms of service.";

繫結到 IsCheckedBind to IsChecked

使用 IsChecked 屬性,以判斷是否選取或清除核取方塊。Use the IsChecked property to determine whether the check box is checked or cleared. 您可以將 IsChecked 屬性的值繫結到另一個二進位值。You can bind the value of the IsChecked property to another binary value. 不過,因為 IsChecked 是可為 null 的布林值,所以您必須使用轉型或值轉換器,才能將其繫結到布林值屬性。However, because IsChecked is a nullable boolean value, you must either use a cast or a value converter to bind it to a boolean property. 這取決於您所使用的實際繫結類型,而您會在下面找到每個可能類型的範例。This depends on the actual binding type you are using and you will find examples below for each possible type.

在這個範例中,用於同意服務條款之核取方塊的 IsChecked 屬性會繫結到 [提交] 按鈕的 IsEnabled 屬性。In this example, the IsChecked property of the check box to agree to terms of service is bound to the IsEnabled property of a Submit button. 唯有當您同意服務條款時,才會啟用 [提交] 按鈕。The Submit button is enabled only if the terms of service are agreed to.

使用 x:BindUsing x:Bind

請注意  我們只顯示相關的程式碼。Note  We only show the relevant code here. 如需資料繫結的詳細資訊,請參閱資料繫結概觀For more info about data binding see Data binding overview. 這裡詳述特定 {x:Bind} 資訊 (例如轉型)。Specific {x:Bind} info (such as casting) is detailed here.

<StackPanel Grid.Column="2" Margin="40">
    <CheckBox x:Name="termsOfServiceCheckBox" Content="I agree to the terms of service."/>
    <Button Content="Submit" 
            IsEnabled="{x:Bind (x:Boolean)termsOfServiceCheckBox.IsChecked, Mode=OneWay}"/>
</StackPanel>

如果此核取方塊也可以是 不確定 狀態,我們會使用繫結的 FallbackValue 屬性來指定代表此狀態的布林值。If the check box can also be in the indeterminate state, we use the binding's FallbackValue property to specify the boolean value representing this state. 在此情況下,我們也不想啟用 [提交] 按鈕:In this case, we don't want to have the Submit button enabled as well:

<Button Content="Submit" 
        IsEnabled="{x:Bind (x:Boolean)termsOfServiceCheckBox.IsChecked, Mode=OneWay, FallbackValue=False}"/>

使用 x:Bind 或 BindingUsing x:Bind or Binding

請注意  我們只會在此顯示使用 {x:Bind} 的相關程式碼。Note  We only show the relevant code here using {x:Bind}. 在 {Binding} 範例中,我們會將 {x:Bind} 取代為 {Binding}。In the {Binding} example, we would replace {x:Bind} with {Binding}. 如需有關資料繫結、值轉換器以及 {x:Bind} 和 {Binding} 標記擴充之間差異的詳細資訊,請參閱資料繫結概觀For more info about data binding, value converters and differences between the {x:Bind} and {Binding} markup extensions, see Data binding overview.

...
<Page.Resources>
    <local:NullableBooleanToBooleanConverter x:Key="NullableBooleanToBooleanConverter"/>
</Page.Resources>

...

<StackPanel Grid.Column="2" Margin="40">
    <CheckBox x:Name="termsOfServiceCheckBox" Content="I agree to the terms of service."/>
    <Button Content="Submit" 
            IsEnabled="{x:Bind termsOfServiceCheckBox.IsChecked, 
                        Converter={StaticResource NullableBooleanToBooleanConverter}, Mode=OneWay}"/>
</StackPanel>
public class NullableBooleanToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value is bool?)
        {
            return (bool)value;
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        if (value is bool)
            return (bool)value;
        return false;
    }
}

處理 Click 和 Checked 事件Handle Click and Checked events

若要在核取方塊狀態變更時執行動作,您可以處理 Click 事件,或者 CheckedUnchecked 事件。To perform an action when the check box state changes, you can handle either the Click event, or the Checked and Unchecked events.

Click 事件會在已核取的狀態變更時發生。The Click event occurs whenever the checked state changes. 如果要處理 Click 事件,請使用 IsChecked 屬性來判斷核取方塊的狀態。If you handle the Click event, use the IsChecked property to determine the state of the check box.

CheckedUnchecked 事件會單獨發生。The Checked and Unchecked events occur independently. 如果您處理這些事件,您應該同時處理這兩個事件,以回應核取方塊中的狀態變更。If you handle these events, you should handle both of them to respond to state changes in the check box.

在下列範例中,我們會示範如何處理 Click 事件,以及 Checked 和 Unchecked 事件。In the following examples, we show handling the Click event, and the Checked and Unchecked events.

多個核取方塊可以共用相同的事件處理常式。Multiple checkboxes can share the same event handler. 這個範例會建立四個核取方塊來選取披薩餡料。This example creates four checkboxes for selecting pizza toppings. 這四個核取方塊會共用相同的 Click 事件處理常式,來更新選取的餡料清單。The four checkboxes share the same Click event handler to update the list of selected toppings.

<StackPanel Margin="40">
    <TextBlock Text="Pizza Toppings"/>
    <CheckBox Content="Pepperoni" x:Name="pepperoniCheckbox"
              Click="toppingsCheckbox_Click"/>
    <CheckBox Content="Beef" x:Name="beefCheckbox" 
              Click="toppingsCheckbox_Click"/>
    <CheckBox Content="Mushrooms" x:Name="mushroomsCheckbox"
              Click="toppingsCheckbox_Click"/>
    <CheckBox Content="Onions" x:Name="onionsCheckbox"
              Click="toppingsCheckbox_Click"/>

    <!-- Display the selected toppings. -->
    <TextBlock Text="Toppings selected:"/>
    <TextBlock x:Name="toppingsList"/>
</StackPanel>

以下是 Click 事件的事件處理常式。Here's the event handler for the Click event. 每次按一下核取方塊時,它會檢查核取方塊以查看哪些方塊已核取,並更新選取的餡料清單。Every time a checkbox is clicked, it examines the checkboxes to see which ones are checked and update list of selected toppings.

private void toppingsCheckbox_Click(object sender, RoutedEventArgs e)
{
    string selectedToppingsText = string.Empty;
    CheckBox[] checkboxes = new CheckBox[] { pepperoniCheckbox, beefCheckbox,
                                             mushroomsCheckbox, onionsCheckbox };
    foreach (CheckBox c in checkboxes)
    {
        if (c.IsChecked == true)
        {
            if (selectedToppingsText.Length > 1)
            {
                selectedToppingsText += ", ";
            }
            selectedToppingsText += c.Content;
        }
    }
    toppingsList.Text = selectedToppingsText;
}

使用不確定狀態Use the indeterminate state

CheckBox 控制項是繼承自 ToggleButton,且可以有三種狀態︰The CheckBox control inherits from ToggleButton and can have three states:

StateState 屬性Property Value
已核取checked IsCheckedIsChecked truetrue
未核取unchecked IsCheckedIsChecked falsefalse
不確定indeterminate IsCheckedIsChecked nullnull

針對要報告不確定狀態的核取方塊,您必須將 IsThreeState 屬性設為 trueFor the check box to report the indeterminate state, you must set the IsThreeState property to true.

將選項分組時,您可以使用不確定的核取方塊來代表整個群組。When options can be grouped, you can use an indeterminate check box to represent the whole group. 當使用者選取群組中部分而非全部的子項目時,請使用核取方塊的不確定狀態。Use the check box's indeterminate state when a user selects some, but not all, sub-items in the group.

在下列範例中,[全選] 核取方塊已將其 IsThreeState 屬性設為 trueIn the following example, the "Select all" checkbox has its IsThreeState property set to true. 針對 [全選] 核取方塊,如果已核取所有子元素,就表示已核取,如果未核取所有子元素,就表示未核取,否則即為不確定狀態。The "Select all" checkbox is checked if all child elements are checked, unchecked if all child elements are unchecked, and indeterminate otherwise.

<StackPanel>
    <CheckBox x:Name="OptionsAllCheckBox" Content="Select all" IsThreeState="True" 
              Checked="SelectAll_Checked" Unchecked="SelectAll_Unchecked" 
              Indeterminate="SelectAll_Indeterminate"/>
    <CheckBox x:Name="Option1CheckBox" Content="Option 1" Margin="24,0,0,0" 
              Checked="Option_Checked" Unchecked="Option_Unchecked" />
    <CheckBox x:Name="Option2CheckBox" Content="Option 2" Margin="24,0,0,0" 
              Checked="Option_Checked" Unchecked="Option_Unchecked" IsChecked="True"/>
    <CheckBox x:Name="Option3CheckBox" Content="Option 3" Margin="24,0,0,0"
              Checked="Option_Checked" Unchecked="Option_Unchecked" />
</StackPanel>
private void Option_Checked(object sender, RoutedEventArgs e)
{
    SetCheckedState();
}

private void Option_Unchecked(object sender, RoutedEventArgs e)
{
    SetCheckedState();
}

private void SelectAll_Checked(object sender, RoutedEventArgs e)
{
    Option1CheckBox.IsChecked = Option2CheckBox.IsChecked = Option3CheckBox.IsChecked = true;
}

private void SelectAll_Unchecked(object sender, RoutedEventArgs e)
{
    Option1CheckBox.IsChecked = Option2CheckBox.IsChecked = Option3CheckBox.IsChecked = false;
}

private void SelectAll_Indeterminate(object sender, RoutedEventArgs e)
{
    // If the SelectAll box is checked (all options are selected), 
    // clicking the box will change it to its indeterminate state.
    // Instead, we want to uncheck all the boxes,
    // so we do this programatically. The indeterminate state should
    // only be set programatically, not by the user.

    if (Option1CheckBox.IsChecked == true &&
        Option2CheckBox.IsChecked == true &&
        Option3CheckBox.IsChecked == true)
    {
        // This will cause SelectAll_Unchecked to be executed, so
        // we don't need to uncheck the other boxes here.
        OptionsAllCheckBox.IsChecked = false;
    }
}

private void SetCheckedState()
{
    // Controls are null the first time this is called, so we just 
    // need to perform a null check on any one of the controls.
    if (Option1CheckBox != null)
    {
        if (Option1CheckBox.IsChecked == true &&
            Option2CheckBox.IsChecked == true &&
            Option3CheckBox.IsChecked == true)
        {
            OptionsAllCheckBox.IsChecked = true;
        }
        else if (Option1CheckBox.IsChecked == false &&
            Option2CheckBox.IsChecked == false &&
            Option3CheckBox.IsChecked == false)
        {
            OptionsAllCheckBox.IsChecked = false;
        }
        else
        {
            // Set third state (indeterminate) by setting IsChecked to null.
            OptionsAllCheckBox.IsChecked = null;
        }
    }
}

可行與禁止事項Do's and don'ts

  • 確認核取方塊的目的和目前狀態非常明確。Verify that the purpose and current state of the check box is clear.

  • 將核取方塊文字內容限制在兩行以內。Limit check box text content to no more than two lines.

  • 核取方塊標籤的措辭陳述應該是有核取記號表示「是」,沒有核取記號則是「否」。Word the checkbox label as a statement that the check mark makes true and the absence of a check mark makes false.

  • 除非您的品牌指導方針指示您使用其他字型,否則使用預設字型。Use the default font unless your brand guidelines tell you to use another.

  • 如果文字內容是動態的,請考慮如何調整控制項的大小以及調整後周圍的視覺項目會發生什麼變化。If the text content is dynamic, consider how the control will resize and what will happen to visuals around it.

  • 如果有兩個或多個互斥選項可供選擇,請考慮使用選項按鈕If there are two or more mutually exclusive options from which to choose, consider using radio buttons.

  • 不要並列核取方塊群組。Don't put two check box groups next to each other. 使用群組標籤分隔群組。Use group labels to separate the groups.

  • 不要使用核取方塊做為開/關控制項或執行命令;請改用切換開關。Don't use a check box as an on/off control or to perform a command; instead, use a toggle switch.

  • 不要使用核取方塊顯示其他控制項 (例如對話方塊)。Don't use a check box to display other controls, such as a dialog box.

  • 使用不確定狀態,指示為部分子選項 (而非全部子選項) 設定某個選項。Use the indeterminate state to indicate that an option is set for some, but not all, sub-choices.

  • 使用不確定狀態時,使用附屬核取方塊來顯示選取或未選取哪些選項。When using indeterminate state, use subordinate check boxes to show which options are selected and which are not. 設計讓使用者可以看到子選項的 UI。Design the UI so that the user can get see the sub-choices.

  • 不要使用不確定狀態來表示第三個狀態。Don't use the indeterminate state to represent a third state. 不確定狀態是用來指示選項僅適用於部分子選項 (而非全部子選項)。The indeterminate state is used to indicate that an option is set for some, but not all, sub-choices. 所以,不要讓使用者直接設定不確定狀態。So, don't allow users to set an indeterminate state directly. 對於不應該執行的範例,此核取方塊使用不確定狀態來指示中等辣度:For an example of what not to do, this check box uses the indeterminate state to indicate medium spiciness:

    不確定核取方塊

    改用含三個選項的選項按鈕群組:「不辣」、「辣」以及「非常辣」。Instead, use a radio button group that has three options: Not spicy, Spicy, and Extra spicy.

    選項按鈕群組有三種選項:「不辣」、「辣」以及「非常辣」

取得範例程式碼Get the sample code