Share via


HOW TO:偵測 RadioButton 選取項目

更新:2007 年 11 月

RadioButton 控制項群組在一起時,各按鈕是互斥 (Mutually Exclusive) 的。在 RadioButton 群組中,使用者一次只能選取一個項目。當使用者選取新的項目時,應用程式即會以程式設計方式清除已選取的項目。RadioButton 是否已選取,取決於其 IsChecked 屬性的狀態。您可以將 RadioButton 控制項放置於父代 (Parent) 內或為其指定群組名稱,以將這些控制項群組在一起。下列程式碼範例將同時執行這兩個動作;RadioButton 控制項是 StackPanel 的子項目,而群組名稱為 ExpandDirectionProperty。

選取 RadioButton 時,會引發 Checked 事件。如下列程式碼範例所示,如果您的應用程式必須在 RadioButton 選取項目變更時執行某個動作,您可以加入事件處理常式來處理 Checked 事件。

範例

<StackPanel>
  <RadioButton Name="ExpandDown" Margin="0,10,0,10" 
            IsChecked="True"
            Checked="ChangeExpandDirection"
            GroupName="ExpandDirectionProperty">
     Expand Down
  </RadioButton>
  <RadioButton Name="ExpandUp" Margin="0,0,0,10"
            Checked="ChangeExpandDirection"
            GroupName="ExpandDirectionProperty">
     Expand Up
  </RadioButton>
  <RadioButton Name="ExpandLeft" Margin="0,0,0,10"
            Checked="ChangeExpandDirection"
            GroupName="ExpandDirectionProperty">
    Expand Left
  </RadioButton>
  <RadioButton Name="ExpandRight" Margin="0,0,0,10"
            Checked="ChangeExpandDirection"
            GroupName="ExpandDirectionProperty">
    Expand Right
  </RadioButton>
</StackPanel>
Private Sub ChangeExpandDirection(ByVal Sender As Object, ByVal e As RoutedEventArgs)
    If (ExpandDown.IsChecked) Then
        myExpander.ExpandDirection = ExpandDirection.Down
    ElseIf (ExpandUp.IsChecked) Then
        myExpander.ExpandDirection = ExpandDirection.Up
    ElseIf (ExpandLeft.IsChecked) Then
        myExpander.ExpandDirection = ExpandDirection.Left
    ElseIf (ExpandRight.IsChecked) Then
        myExpander.ExpandDirection = ExpandDirection.Right
    End If

    'Expand myExpander so it is easier to see the effect of changing 
    'the ExpandDirection property for My Expander
    myExpander.IsExpanded = True
End Sub
private void ChangeExpandDirection(object sender, RoutedEventArgs e)
{
    if ((Boolean)ExpandDown.IsChecked)
        myExpander.ExpandDirection = ExpandDirection.Down;
    else if ((Boolean)ExpandUp.IsChecked)
        myExpander.ExpandDirection = ExpandDirection.Up;
    else if ((Boolean)ExpandLeft.IsChecked)
        myExpander.ExpandDirection = ExpandDirection.Left;
    else if ((Boolean)ExpandRight.IsChecked)
        myExpander.ExpandDirection = ExpandDirection.Right;

    //Expand myExpander so it is easier to see the effect of changing 
    //the ExpandDirection property for My Expander
    myExpander.IsExpanded = true;
}