選項按鈕Radio buttons

選項按鈕可讓使用者從兩個或多個互斥但相關的選項集合中選取一個選項。Radio buttons, also called option buttons, let users select one option from a collection of two or more mutually exclusive, but related, options. 選項按鈕一律會在群組中使用,而且每個選項都會由群組中的一個選項按鈕來表示。Radio buttons are always used in groups, and each option is represented by one radio button in the group.

在預設狀態下,不會選取 RadioButtons 群組中的任何選項按鈕。In the default state, no radio button in a RadioButtons group is selected. 也就是說,清除所有選項按鈕。That is, all radio buttons are cleared. 不過,一旦使用者選取了選項按鈕,就無法取消選取按鈕而讓群組還原到其初始清除狀態。However, once a user has selected a radio button, the user can't deselect the button to restore the group to its initial cleared state.

RadioButtons 群組的單一行為會與核取方塊 (可支援多重選取和取消選取或清除) 的單一行為有所區別。The singular behavior of a RadioButtons group distinguishes it from check boxes, which support multi-selection and deselection, or clearing.

RadioButtons 群組的範例,其中已選取一個選項按鈕

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

   
WinUI 標誌 RadioButtons控制項包含在 Windows UI 程式庫中;該程式庫是 NuGet 套件,其中包含適用於 Windows 應用程式的新控制項和 UI 功能。The RadioButtons control is included as part of the Windows UI Library, 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.

Windows UI 程式庫 APIRadioButtons 類別SelectedItem 屬性SelectedIndex 屬性SelectionChanged 事件Windows UI Library APIs: RadioButtons class, SelectedItem property, SelectedIndex property, SelectionChanged event

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

重要

RadioButtons 與 RadioButtonRadioButtons vs RadioButton

有兩種方式可建立選項按鈕群組。There are two ways to create radio button groups.

  • 從 WinUI 2.3 開始,我們建議使用 RadioButtons 控制項。Starting with WinUI 2.3, we recommend the RadioButtons control. 此控制項可簡化版面配置、處理鍵盤瀏覽和協助工具,以及支援繫結至資料來源。This control simplifies layout, handles keyboard navigation and accessibility, and supports binding to a data source.
  • 您可以使用個別 RadioButton 控制項的群組。You can use groups of individual RadioButton controls. 如果您的應用程式未使用 WinUI 2.3 或更新版本,則這是唯一的選項。If your app does not use WinUI 2.3 or later, this is the only option.

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

使用選項按鈕可讓使用者從兩個或更多互斥選項中選取。Use radio buttons to let users select from two or more mutually exclusive options.

一個 RadioButtons 群組,其中已選取一個選項按鈕

當使用者需要先查看所有選項再做選擇時,請使用選項按鈕。Use radio buttons when users need to see all options before they make a selection. 選項按鈕同等地強調所有選項,這表示有些選項可能會引起不必要或不想要的注意。Radio buttons emphasize all options equally, which means that some options might draw more attention than is necessary or desired.

除非所有選項都值得同等注意,否則請考慮使用其他控制項。Unless all options deserve equal attention, consider using other controls. 例如,若要為大多數使用者以及在大部分情況下建議單一最佳選項,請使用下拉式方塊,將該最佳選項顯示為預設選項。For example, to recommend a single best option for most users and in most situations, use a combo box to display that best option as the default option.

顯示預設選項的下拉式方塊

如果只有兩個可以明確表達為單一二元選擇的可能選項 (例如「開啟/關閉」或「是/否」),請將這兩個選項結合成單一的核取方塊切換開關控制項。If there are only two possible options that can be expressed clearly as a single binary choice, such as on/off or yes/no, combine them into a single check box or toggle switch control. 例如,使用「我同意」的單一核取方塊來代替「我同意」和「我不同意」兩個選項按鈕。For example, use a single check box for "I agree" instead of two radio buttons for "I agree" and "I don't agree."

請勿對單一的二元選擇使用兩個選項按鈕:Don't use two radio buttons for a single binary choice:

呈現二元選擇的兩個選項按鈕

請改為使用核取方塊:Use a check box instead:

核取方塊是呈現二進位選擇的不錯替代方式

使用者可以選取多個選項時,請使用核取方塊When users can select multiple options, use check boxes.

核取方塊支援多重選取

當使用者的選項位於某個範圍內的值 (例如,10、20、30、...100) 時,請使用 滑桿控制項。When users' options lie within a range of values (for example, 10, 20, 30, ... 100), use a slider control.

滑桿控制項,其中顯示值範圍內的某個值

如果有超過 8 個選項,請使用下拉式方塊If there are more than eight options, use a combo box.

顯示多個選項的清單方塊

如果可用的選項取決於應用程式目前的內容,或者可能會不斷地變化,請使用清單控制項。If the available options are based on an app's current context, or they can otherwise vary dynamically, use a list control.

範例Examples

XAML 控制項庫XAML Controls Gallery
The XAML Controls Gallery app icon

如果您已安裝 XAML 控制項庫應用程式,請開啟應用程式以查看 RadioButtons 控制項的運作情形If you have the XAML Controls Gallery app installed, open it to see the RadioButtons control in action.

WinUI RadioButtons 概觀WinUI RadioButtons overview

RadioButtons 控制項已將鍵盤存取和瀏覽行為最佳化。Keyboard access and navigation behavior have been optimized in the RadioButtons control. 這些改善可同時協助鍵盤和協助工具進階使用者在選項清單中更快速且輕鬆地移動。These improvements help both accessibility and keyboard power users move through the list of options more quickly and easily.

除了這些改善之外,RadioButtons 群組中個別選項按鈕的預設視覺版面配置也已透過自動化方向、間距和邊界設定進行最佳化。In addition to these improvements, the default visual layout of individual radio buttons in a RadioButtons group has been optimized through automated orientation, spacing, and margin settings. 此最佳化消除了指定這些屬性的需求,因為您在使用更基本的群組控制項 例如 StackPanelGird 時可能必須這麼做。This optimization eliminates the requirement to specify these properties, as you might have to do when you use a more primitive grouping control, such as StackPanel or Grid.

RadioButtons 控制項具有特殊的瀏覽行為,可協助鍵盤使用者更快速且更輕鬆地瀏覽清單。The RadioButtons control has special navigation behavior that helps keyboard users navigate the list more quickly and more easily.

鍵盤焦點Keyboard focus

RadioButtons 控制項支援兩種狀態:The RadioButtons control supports two states:

  • 未選取任何選項按鈕No radio button is selected
  • 已選取一個選項按鈕One radio button is selected

後面幾節將說明控制項在這兩種狀態中各自的焦點行為。The next sections describe the focus behavior of the control in each state.

未選取任何選項按鈕No radio button is selected

未選取任何選項按鈕時,清單中的第一個選項按鈕會取得焦點。When no radio button is selected, the first radio button in the list gets focus.

注意

不會選取從初始 Tab 瀏覽接收 Tab 焦點的項目。The item that receives tab focus from the initial tab navigation is not selected.

不具 Tab 焦點,且沒有選取項目的清單List without tab focus, no selection

不具 Tab 焦點,而且沒有已選取項目的清單

不具初始 Tab 焦點,且沒有選取項目的清單List with initial tab focus, no selection

具有初始 Tab 焦點,而且沒有已選取項目的清單

已選取一個選項按鈕One radio button is selected

當使用者透過 Tab 鍵進入已選取選項按鈕的清單時,選取的選項按鈕就會取得焦點。When a user tabs into the list where a radio button is already selected, the selected radio button gets focus.

不具 Tab 焦點的清單List without tab focus

不具 Tab 焦點和已選取項目的清單

具有初始 Tab 焦點的清單List with initial tab focus

具有初始 Tab 焦點和已選取項目的清單

鍵盤瀏覽Keyboard navigation

如需一般鍵盤瀏覽行為的詳細資訊,請參閱鍵盤互動 - 瀏覽For more information about general keyboard navigation behaviors, see Keyboard interactions - Navigation.

RadioButtons 群組中的項目已有焦點時,使用者可以使用方向鍵在群組內的項目之間進行「內部瀏覽」。When an item in a RadioButtons group already has focus, the user can use arrow keys for "inner navigation" between the items within the group. 向上鍵和向下鍵會移至 XAML 標記中所定義的「下一個」或「上一個」邏輯項目。The Up and Down arrow keys move to the "next" or "previous" logical item, as defined in your XAML markup. 向左鍵和向右鍵則會進行空間上的移動。The Left and Right arrow keys move spatially.

在單欄或單列的版面配置中,鍵盤瀏覽會產生下列行為:In a single-column or single-row layout, keyboard navigation results in the following behavior:

單欄Single column

單欄 RadioButtons 群組中的鍵盤瀏覽範例

向上鍵和向下鍵會在項目之間移動。The Up arrow and Down arrow keys move between items.
向左鍵和向右鍵鍵不會執行任何動作。The Left arrow and Right arrow keys do nothing.

單一資料列Single row

單列 RadioButtons 群組中的鍵盤瀏覽範例

向左鍵和向上鍵會移至上一個項目,向右鍵和向下鍵則會移至下一個項目。The Left and Up arrow keys move to the previous item, and the Right and Down arrow keys move to the next item.

在多欄、多列的格狀版面配置中,鍵盤瀏覽會產生以下行為:In a multi-column, multi-row grid layout, keyboard navigation results in this behavior:

向左鍵/向右鍵Left/Right arrow keys

多欄/列 RadioButtons 群組中的水平鍵盤瀏覽範例

向左鍵和向右鍵會在某列的項目之間水平移動焦點。The Left and Right arrow keys move focus horizontally between items in a row.

焦點位於某欄最後一個項目的水平鍵盤瀏覽範例

當焦點位於某欄最後一個項目上,並按下向右鍵或向左鍵時,焦點會移至下一欄或上一欄的最後一個項目 (如果有的話)。When focus is on the last item in a column and the Right or Left arrow key is pressed, focus moves to the last item in the next or previous column (if any).

向上鍵/向下鍵Up/Down arrow keys

多欄/列 RadioButtons 群組中的垂直鍵盤瀏覽範例

向上鍵和向下鍵會在某欄的項目之間垂直移動焦點。The Up and Down arrow keys move focus vertically between items in a column.

焦點位於某欄最後一個項目的垂直鍵盤瀏覽範例

當焦點位於某欄最後一個項目上,並按下向下鍵時,焦點會移至下一欄的第一個項目 (如果有的話)。When focus is on the last item in a column and the Down arrow key is pressed, focus moves to the first item in the next column (if any). 當焦點位於某欄第一個項目上,並按下向上鍵時,焦點會移至上一欄的最後一個項目 (如果有的話)When focus is on the first item in a column and the Up arrow key is pressed, focus moves to the last item in the previous column (if any)

如需詳細資訊,請參閱鍵盤互動For more information, see Keyboard interactions.

換行Wrapping

RadioButtons 群組不會將焦點從第一列或第一欄換行至最後一列或最後一欄,也不會從最後一列或最後一欄換行至第一列或第一欄。The RadioButtons group doesn't wrap focus from the first row or column to the last, or from the last row or column to the first. 這是因為當使用螢幕助讀程式時,界限的意義以及開始和結束的清楚指示會遺失,這使得視力受損的使用者難以瀏覽清單。This is because, when users use a screen reader, a sense of boundary and a clear indication of beginning and end is lost, which makes it difficult for users with visual impairment to navigate the list.

RadioButtons 控制項也不支援列舉,因為控制項的用意是要包含合理的項目數 (請參閱這是正確的控制項嗎?)。The RadioButtons control also doesn't support enumeration, because the control is intended to contain a reasonable number of items (see Is this the right control?).

選取項目追隨焦點Selection follows focus

當您使用鍵盤在 RadioButtons 群組中的項目之間瀏覽時,當焦點從某個項目移至下一個項目時,就會選取新聚焦的項目,並清除先前聚焦的項目。When you use the keyboard to navigate between items in a RadioButtons group, as focus moves from one item to the next, the newly focused item gets selected and the previously focused item is cleared.

鍵盤瀏覽之前Before keyboard navigation

鍵盤瀏覽之前的焦點和選取範例

鍵盤瀏覽之前的焦點和選取項目。Focus and selection before keyboard navigation.

鍵盤瀏覽之後After keyboard navigation

鍵盤瀏覽之後的焦點和選取範例

鍵盤瀏覽之後的焦點和選取項目,其中的向下鍵會將焦點移至選項按鈕 3,選取此選項按鈕,然後清除選項按鈕 2。Focus and selection after keyboard navigation, where the Down arrow key moves focus to radio button 3, selects it, and clears radio button 2.

您可以使用「Ctrl+方向鍵」來進行瀏覽,以便移動焦點而不變更選取項目。You can move focus without changing selection by using Ctrl+arrow keys to navigate. 焦點移動之後,您可以使用空格鍵來選取焦點目前所在的項目。After focus is moved, you can use the Spacebar to select the item that currently has focus.

如果您使用 Xbox 遊戲台或遙控器在選項按鈕之間移動,則會停用「選取項目追隨焦點」行為,而且使用者必須按下 "A" 鍵才能選取焦點目前所在的選項按鈕。If you use an Xbox gamepad or remote control to move between radio buttons, the "selection follows focus" behavior is disabled, and the user must press the "A" button to select the radio button that currently has focus.

協助工具行為Accessibility behavior

下表描述朗讀程式如何處理 RadioButtons 群組和宣告的內容。The following table describes how Narrator handles a RadioButtons group and what is announced. 這種行為取決於使用者如何設定朗讀程式詳細資料喜好設定。This behavior depends on how a user has set the Narrator detail preferences.

動作Action 朗讀程式公告Narrator announcement
焦點移至選取的項目Focus moves to a selected item 名稱 RadioButton 已選取第 x 項,共 N 項」"name, RadioButton, selected, x of N"
焦點移至未選取的項目Focus moves to an unselected item
(如果使用 Ctrl-方向鍵或 Xbox 遊戲台進行瀏覽,
這表示選取項目不會追隨焦點。)
(If navigating with Ctrl-arrow keys or Xbox gamepad,
which indicates selection is not following focus.)
名稱 RadioButton 未選取第 x 項,共 N 項」"name, RadioButton, non-selected, x of N"

注意

朗讀程式針對每個項目所公告的 名稱AutomationProperties.Name 已連結屬性的值 (如果可供項目使用);否則,該名稱會是項目的 ToString 方法所傳回的值。The name that Narrator announces for each item is the value of the AutomationProperties.Name attached property if it is available for the item; otherwise, it is the value returned by the item's ToString method.

x 是目前項目的編號。x is the number of the current item. N 是群組中的項目總數。N is the total number of items in the group.

建立 WinUI RadioButtons 群組Create a WinUI RadioButtons group

RadioButtons 控制項會使用類似 ItemsControl 的內容模型。The RadioButtons control uses a content model similar to an ItemsControl. 這表示您可以:This means that you can:

提示

在這整份文件中,我們使用 XAML 中的 muxc 別名來代表我們已加入專案中的 Windows UI 程式庫 API。Throughout this document, we use the muxc alias in XAML to represent the Windows UI Library APIs that we have included in our project. 我們已將此新增至我們的 Page 元素:xmlns:muxc="using:Microsoft.UI.Xaml.Controls"We have added this to our Page element: xmlns:muxc="using:Microsoft.UI.Xaml.Controls"

在後方的程式碼中,我們也使用 C# 中的 muxc 別名來代表我們已加入專案中的 Windows UI 程式庫 API。In the code-behind, we also use the muxc alias in C# to represent the Windows UI Library APIs that we have included in our project. 我們已在檔案頂端新增了此 using 陳述式:using muxc = Microsoft.UI.Xaml.Controls;We have added this using statement at the top of the file: using muxc = Microsoft.UI.Xaml.Controls;

在這裡,您將宣告有三個選項的簡單 RadioButtons 控制項。Here, you declare a simple RadioButtons control with three options. 您可以設定 Header 屬性來為群組提供標籤,以及設定 SelectedIndex 屬性來提供預設選項。The Header property is set to give the group a label, and the SelectedIndex property is set to provide a default option.

<muxc:RadioButtons Header="Background color"
                   SelectedIndex="0"
                   SelectionChanged="BackgroundColor_SelectionChanged">
    <x:String>Red</x:String>
    <x:String>Green</x:String>
    <x:String>Blue</x:String>
</muxc:RadioButtons>

結果如下所示:The result looks like this:

三個選項按鈕的群組

若要在使用者選取選項時採取動作,請處理 SelectionChanged 事件。To take an action when the user selects an option, handle the SelectionChanged event. 在這裡,您會變更名為 "ExampleBorder" (<Border x:Name="ExampleBorder" Width="100" Height="100"/>) 的 Border 元素背景色彩。Here, you change the background color of a Border element named "ExampleBorder" (<Border x:Name="ExampleBorder" Width="100" Height="100"/>).

private void BackgroundColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (ExampleBorder != null && sender is muxc.RadioButtons rb)
    {
        string colorName = rb.SelectedItem as string;
        switch (colorName)
        {
            case "Red":
                ExampleBorder.Background = new SolidColorBrush(Colors.Red);
                break;
            case "Green":
                ExampleBorder.Background = new SolidColorBrush(Colors.Green);
                break;
            case "Blue":
                ExampleBorder.Background = new SolidColorBrush(Colors.Blue);
                break;
        }
    }
}

提示

您也可以從 SelectionChangedEventArgs.AddedItems 屬性取得所選的項目。You can also get the selected item from the SelectionChangedEventArgs.AddedItems property. 只會有一個位於索引 0 的已選取項目,因此您可以獲得如下的已選取項目:string colorName = e.AddedItems[0] as string;There will only be one selected item, at index 0, so you could get the selected item like this: string colorName = e.AddedItems[0] as string;.

選取狀態Selection states

選項按鈕有兩個狀態:已選取或已清除。A radio button has two states: selected or cleared. RadioButtons 群組中選取了選項時,您可以從 SelectedItem 屬性獲得其值,並從 SelectedIndex 屬性獲得其在集合中的位置。When an option is selected in a RadioButtons group, you can get its value from the SelectedItem property, and its location in the collection from the SelectedIndex property. 如果使用者選取同一個群組中的另一個選項按鈕,則可清除選項按鈕,但如果使用者再次選取,則無法將其清除。A radio button can be cleared if a user selects another radio button in the same group, but it can't be cleared if the user selects it again. 不過,您可以將選項按鈕群組設定為 SelectedItem = nullSelectedIndex = -1,以程式設計方式清除該選項按鈕。However, you can clear a radio button group programmatically by setting it SelectedItem = null, or SelectedIndex = -1. (將 SelectedIndex 設定為 Items 集合範圍以外的任何值,會產生未選取任何項目的狀態)。(Setting SelectedIndex to any value outside the range of the Items collection results in no selection.)

RadioButtons 內容RadioButtons content

在上述範例中,您已使用簡單的字串填入 RadioButtons 控制項。In the previous example, you populated the RadioButtons control with simple strings. 此控制項會提供幾個選項按鈕,並使用字串作為每一個選項按鈕的標籤。The control provided the radio buttons, and used the strings as the label for each one.

不過,您可以使用任何物件來填入 RadioButtons 控制項。However, you can populate the RadioButtons control with any object. 一般來說,您會希望物件提供可作為文字標籤的字串標記法。Typically, you want the object to provide a string representation that can be used as a text label. 在某些情況下,可能適合使用影像來取代文字。In some cases, an image might be appropriate in place of text.

在這裡,我們使用 SymbolIcon 元素來填入控制項。Here, SymbolIcon elements are used to populate the control.

<muxc:RadioButtons Header="Choose the icon without an arrow">
    <SymbolIcon Symbol="Back"/>
    <SymbolIcon Symbol="Attach"/>
    <SymbolIcon Symbol="HangUp"/>
    <SymbolIcon Symbol="FullScreen"/>
</muxc:RadioButtons>

具有符號圖示的群組選項按鈕

您也可以使用個別的 RadioButton 控制項來填入 RadioButtons 項目。You can also use individual RadioButton controls to populate the RadioButtons items. 我們稍後會討論這個特殊案例。This is a special case that we discuss later. 請參閱 RadioButtons 群組中的 RadioButton 控制項See RadioButton controls in a RadioButtons group.

能夠使用任何物件的優點是,您可以將 RadioButtons 控制項繫結至資料模型中的自訂類型。A benefit of being able to use any object is that you can bind the RadioButtons control to a custom type in your data model. 下一節將示範這種情況。The next section demonstrates this.

資料繫結Data binding

RadioButtons 控制項支援將資料繫結至其 ItemsSource 屬性。The RadioButtons control supports data binding to its ItemsSource property. 這個範例會示範如何將控制項繫結至自訂資料來源。This example shows how you can bind the control to a custom data source. 這個範例的外觀和功能與先前的背景色彩範例相同,但在這裡,色彩筆刷會儲存在資料模型中,而不會建立在 SelectionChanged 事件處理常式中。The appearance and functionality of this example is the same as the previous background color example, but here, the color brushes are stored in the data model instead of being created in the SelectionChanged event handler.

 <muxc:RadioButtons Header="Background color"
                    SelectedIndex="0"
                    SelectionChanged="BackgroundColor_SelectionChanged"
                    ItemsSource="{x:Bind colorOptionItems}"/>
public sealed partial class MainPage : Page
{
    // Custom data item.
    public class ColorOptionDataModel
    {
        public string Label { get; set; }
        public SolidColorBrush ColorBrush { get; set; }

        public override string ToString()
        {
            return Label;
        }
    }

    List<ColorOptionDataModel> colorOptionItems;

    public MainPage1()
    {
        this.InitializeComponent();

        colorOptionItems = new List<ColorOptionDataModel>();
        colorOptionItems.Add(new ColorOptionDataModel()
            { Label = "Red", ColorBrush = new SolidColorBrush(Colors.Red) });
        colorOptionItems.Add(new ColorOptionDataModel()
            { Label = "Green", ColorBrush = new SolidColorBrush(Colors.Green) });
        colorOptionItems.Add(new ColorOptionDataModel()
            { Label = "Blue", ColorBrush = new SolidColorBrush(Colors.Blue) });
    }

    private void BackgroundColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var option = e.AddedItems[0] as ColorOptionDataModel;
        ExampleBorder.Background = option?.ColorBrush;
    }
}

RadioButtons 群組中的 RadioButton 控制項RadioButton controls in a RadioButtons group

您可以使用個別的 RadioButton 控制項來填入 RadioButtons 項目。You can use individual RadioButton controls to populate the RadioButtons items. 您可以執行此動作來存取某些屬性,例如 AutomationProperties.Name;或者,您可能有現有的 RadioButton 程式碼,但想要利用 RadioButtons 的版面配置和瀏覽。You might do this to get access to certain properties, like AutomationProperties.Name; or you might have existing RadioButton code, but want to take advantage of the layout and navigation of RadioButtons.

<muxc:RadioButtons Header="Background color">
    <RadioButton Content="Red" Tag="red" AutomationProperties.Name="red"/>
    <RadioButton Content="Green" Tag="green" AutomationProperties.Name="green"/>
    <RadioButton Content="Blue" Tag="blue" AutomationProperties.Name="blue"/>
</muxc:RadioButtons>

當您使用 RadioButtons 群組中的 RadioButton 控制項時,RadioButtons 控制項會知道如何呈現 RadioButton,所以您最後不會得到兩個選取項目圓形。When you use RadioButton controls in a RadioButtons group, the RadioButtons control knows how to present the RadioButton, so you won't end up with two selection circles.

不過,有一些您應該注意的行為。However, there are some behaviors you should be aware of. 我們建議您在個別控制項或 RadioButtons 上處理狀態和事件,但不要同時在兩者上進行,以免發生衝突。We recommend that you handle state and events on the individual controls or on RadioButtons, but not both, to avoid conflicts.

下表顯示這兩個控制項的相關事件和屬性。This table shows the related events and properties on both controls.

RadioButtonRadioButton RadioButtonsRadioButtons
已核取未核取按一下Checked, Unchecked, Click SelectionChanged (英文)SelectionChanged
IsCheckedIsChecked SelectedItemSelectedIndexSelectedItem, SelectedIndex

如果您在個別 RadioButton 上處理事件 (例如 CheckedUnchecked),同時也處理 RadioButtons.SelectionChanged 事件,則這兩個事件都會引發。If you handle events on an individual RadioButton, such as Checked or Unchecked, and also handle the RadioButtons.SelectionChanged event, both events will fire. RadioButton 事件會先發生,然後 RadioButtons.SelectionChanged 事件再發生,這可能會導致衝突。The RadioButton event occurs first, and then the RadioButtons.SelectionChanged event occurs, which could result in conflicts.

IsCheckedSelectedItemSelectedIndex 屬性會保持同步。The IsChecked, SelectedItem, and SelectedIndex properties stay synchronized. 變更其中一個屬性會更新其他兩個屬性。A change to one property updates the other two.

RadioButton.GroupName 屬性會遭到忽略。The RadioButton.GroupName property is ignored. 此群組是由 RadioButtons 控制項建立的。The group is created by the RadioButtons control.

定義多欄Defining multiple columns

根據預設,RadioButtons 控制項會在單欄中垂直排列其選項按鈕。By default, the RadioButtons control arranges its radio buttons vertically in a single column. 您可以設定 MaxColumns 屬性,讓控制項將選項按鈕排列在多欄中。You can set the MaxColumns property to make the control arrange the radio buttons in multiple columns. (當您這麼做時,選項按鈕會按照以欄為主的順序進行配置,項目會由上往下填入,然後由左往右填入)。(When you do this, they are laid out in column-major order, where items fill in from top to bottom, then left to right.)

<muxc:RadioButtons Header="Options" MaxColumns="3">
    <x:String>Item 1</x:String>
    <x:String>Item 2</x:String>
    <x:String>Item 3</x:String>
    <x:String>Item 4</x:String>
    <x:String>Item 5</x:String>
    <x:String>Item 6</x:String>
</muxc:RadioButtons>

兩個三欄群組中的選項按鈕

提示

若要讓項目排列在單一水平列中,請將 MaxColumns 設定為等於群組中的項目數。To have items arranged in a single horizontal row, set MaxColumns equal to the number of items in the group.

建立您自己的 RadioButton 群組Create your own RadioButton group

重要

除非您使用舊版的 WinUI,否則我們建議使用 WinUI RadioButtons 控制項將 RadioButton 元素分組。Unless you're using an older version of WinUI, we recommend using the WinUI RadioButtons control to group RadioButton elements.

選項按鈕以群組方式運作。Radio buttons work in groups. 您可以透過下列兩種方式之一,將個別 RadioButton 控制項分組:You can group individual RadioButton controls in either of two ways:

  • 將它們放入同一個父容器。Put them inside the same parent container.
  • 將每個選項按鈕的 GroupName 屬性設定為相同的值。Set the GroupName property on each radio button to the same value.

在這個範例中,第一個選項按鈕群組位於相同的堆疊面板中,藉此以隱含方式群組化。In this example, the first group of radio buttons is implicitly grouped by being in the same stack panel. 第二個群組會分割成兩個堆疊面板,因此會使用 GroupName 來將其明確地分組到單一群組中。The second group is divided between two stack panels, so GroupName is used to explicitly group them into a single group.

<StackPanel>
    <StackPanel>
        <TextBlock Text="Background" Style="{ThemeResource BaseTextBlockStyle}"/>
        <!-- Group 1 - implicit grouping -->
        <StackPanel Orientation="Horizontal">
            <RadioButton Content="Green" Tag="green" Checked="BGRadioButton_Checked"/>
            <RadioButton Content="Yellow" Tag="yellow" Checked="BGRadioButton_Checked"/>
            <RadioButton Content="Blue" Tag="blue" Checked="BGRadioButton_Checked"/>
            <RadioButton Content="White" Tag="white" Checked="BGRadioButton_Checked"
                         IsChecked="True"/>
        </StackPanel>
    </StackPanel>

    <StackPanel>
        <TextBlock Text="BorderBrush" Style="{ThemeResource BaseTextBlockStyle}"/>
        <!-- Group 2 - grouped by GroupName -->
        <StackPanel Orientation="Horizontal">
            <StackPanel>
                <RadioButton Content="Green" Tag="green" GroupName="BorderBrush"
                             Checked="BorderRadioButton_Checked"/>
                <RadioButton Content="Yellow" Tag="yellow" GroupName="BorderBrush"
                             Checked="BorderRadioButton_Checked" IsChecked="True"/>
            </StackPanel>
            <StackPanel>
                <RadioButton Content="Blue" Tag="blue" GroupName="BorderBrush"
                             Checked="BorderRadioButton_Checked"/>
                <RadioButton Content="White" Tag="white"  GroupName="BorderBrush"
                             Checked="BorderRadioButton_Checked"/>
            </StackPanel>
        </StackPanel>
    </StackPanel>
    <Border x:Name="ExampleBorder"
            BorderBrush="#FFFFD700" Background="#FFFFFFFF"
            BorderThickness="10" Height="50" Margin="0,10"/>
</StackPanel>
private void BGRadioButton_Checked(object sender, RoutedEventArgs e)
{
    RadioButton rb = sender as RadioButton;

    if (rb != null && ExampleBorder != null)
    {
        string colorName = rb.Tag.ToString();
        switch (colorName)
        {
            case "yellow":
                ExampleBorder.Background = new SolidColorBrush(Colors.Yellow);
                break;
            case "green":
                ExampleBorder.Background = new SolidColorBrush(Colors.Green);
                break;
            case "blue":
                ExampleBorder.Background = new SolidColorBrush(Colors.Blue);
                break;
            case "white":
                ExampleBorder.Background = new SolidColorBrush(Colors.White);
                break;
        }
    }
}

private void BorderRadioButton_Checked(object sender, RoutedEventArgs e)
{
    RadioButton rb = sender as RadioButton;

    if (rb != null && ExampleBorder != null)
    {
        string colorName = rb.Tag.ToString();
        switch (colorName)
        {
            case "yellow":
                ExampleBorder.BorderBrush = new SolidColorBrush(Colors.Gold);
                break;
            case "green":
                ExampleBorder.BorderBrush = new SolidColorBrush(Colors.DarkGreen);
                break;
            case "blue":
                ExampleBorder.BorderBrush = new SolidColorBrush(Colors.DarkBlue);
                break;
            case "white":
                ExampleBorder.BorderBrush = new SolidColorBrush(Colors.White);
                break;
        }
    }
}

這兩個 RadioButton 控制項群組看起來像這樣:These two groups of RadioButton controls look like this:

兩個群組中的選項按鈕

選項按鈕狀態Radio button states

選項按鈕有兩個狀態:已選取或已清除。A radio button has two states: selected or cleared. 已選取選項按鈕時,其 IsChecked 屬性為 trueWhen a radio button is selected, its IsChecked property is true. 已選取選項按鈕時,其 IsChecked 屬性為 falseWhen a radio button is cleared, its IsChecked property is false. 如果使用者選取同一個群組中的另一個選項按鈕,則可清除選項按鈕,但如果使用者再次選取,則無法將其清除。A radio button can be cleared if a user selects another radio button in the same group, but it can't be cleared if the user selects it again. 不過,您可以將選項按鈕的 IsChecked 屬性設定為 false,以程式設計方式清除該選項按鈕。However, you can clear a radio button programmatically by setting its IsChecked property to false.

要考慮的視覺效果Visuals to consider

個別 RadioButton 控制項的預設間距與 RadioButtons 群組所提供的間距不同。The default spacing of individual RadioButton controls is different than the spacing provided by a RadioButtons group. 若要將 RadioButtons 間距套用到個別 RadioButton 控制項,請使用 0,0,7,3Margin 值,如下所示。To apply the RadioButtons spacing to individual RadioButton controls, use a Margin value of 0,0,7,3, as shown here.

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="RadioButton">
            <Setter Property="Margin" Value="0,0,7,3"/>
        </Style>
    </StackPanel.Resources>
    <TextBlock Text="Background"/>
    <RadioButton Content="Item 1"/>
    <RadioButton Content="Item 2"/>
    <RadioButton Content="Item 3"/>
</StackPanel>

下列影像顯示群組中的選項按鈕慣用間距。The following images show the preferred spacing of radio buttons in a group.

顯示一組選項按鈕的影像,這些選項按鈕垂直排列

顯示選項按鈕間距指導方針的影像

注意

如果您使用 WinUI RadioButtons 控制項,則間距、邊界和方向均已最佳化。If you're using a WinUI RadioButtons control, the spacing, margins, and orientation are already optimized.

建議Recommendations

  • 確定一組選項按鈕的目的和目前狀態明確。Make sure that the purpose and current state of a set of radio buttons is explicit.
  • 將選項按鈕的文字標籤限制為單行。Limit the radio button's text label to a single line.
  • 如果文字標籤是動態的,請考慮按鈕將如何自動調整大小以及調整後周圍的任何視覺效果會發生什麼變化。If the text label is dynamic, consider how the button will automatically resize and what will happen to any visuals around it.
  • 除非您的品牌指導方針指示您使用其他字型,否則使用預設字型。Use the default font unless your brand guidelines tell you otherwise.
  • 不要將兩個 RadioButtons 群組並排。Don't put two RadioButtons groups side by side. 當兩個 RadioButtons 群組並列時,使用者很難判斷哪個按鈕屬於哪個群組。When two RadioButtons groups are right next to each other, it can be difficult for users to determine which buttons belong to which group.

取得範例程式碼Get the sample code