概要
この記事では、WPFのRadioButtonコントロールをグループ化して選択の一意性を確保する方法について説明します。RadioButtonは複数の選択肢を提供する際に使用されますが、個々のRadioButtonをグループ化することで、同じグループ内では一つの選択肢しか選択できなくなります。この記事では、RadioButtonのグループ化方法について解説します。
構文
RadioButtonをグループ化するには、同じGroupNameプロパティの値を設定します。GroupNameプロパティはRadioButtonが所属するグループを識別するための文字列です。同じGroupNameを持つRadioButtonは一つのグループとみなされ、一意性が確保されます。
<StackPanel> <RadioButton GroupName="group1" Content="選択肢1" /> <RadioButton GroupName="group1" Content="選択肢2" /> <RadioButton GroupName="group1" Content="選択肢3" /> </StackPanel>
上記の例では、3つのRadioButtonが同じ”group1″というGroupNameを持つため、一つのグループとして扱われます。
使用例
以下の例では、RadioButtonをグループ化して異なる言語の選択肢を表示し、選択された言語に応じてメッセージを表示する方法を示します。
XAMLコード:
<StackPanel> <TextBlock Text="色を選択してください:" /> <RadioButton GroupName="color" Content="赤" Checked="RadioButton_Checked" /> <RadioButton GroupName="color" Content="緑" Checked="RadioButton_Checked" /> <RadioButton GroupName="color" Content="青" Checked="RadioButton_Checked" /> </StackPanel>
C#コード:
private void RadioButton_Checked(object sender, RoutedEventArgs e) { RadioButton radioButton = sender as RadioButton; string selectedColor = radioButton.Content.ToString(); MessageBox.Show($"選択された色は「{selectedColor}」です。"); }
上記の例では、RadioButtonを”color”というGroupNameでグループ化しています。選択された色に応じてメッセージボックスが表示されます。
Please follow and like us:
コメント