LoginSignup
8
8

More than 5 years have passed since last update.

WPF ラジオボタンのグルーピングで引っかかった点

Posted at

WPFのアプリケーションを開発していて、ラジオボタンを用いたUserControlで引っかかった箇所があったので書いておきます。

ラジオボタンをグルーピングするには、RadioButton コントロールのGroupNameに同一の名称を設定します。通常であればそれで問題ありませんが、ラジオボタンをUserControlに配置する場合は注意が必要となります。

例えば、以下のソースのようにラジオボタンを持つUserControlを作成し、Window上に複数ならべて配置したとします。

RadioButtonTestControl.xaml
<UserControl x:Class="RadioTest.RadioButtonTestControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="100" d:DesignWidth="200">
    <Grid>
        <Border BorderBrush="Black" BorderThickness="1">
            <StackPanel Orientation="Vertical">
                <RadioButton Name="btn1" GroupName="buttons" Margin="10">ラジオボタン1</RadioButton>
                <RadioButton Name="btn2" GroupName="buttons" Margin="10">ラジオボタン2</RadioButton>
                <RadioButton Name="btn3" GroupName="buttons" Margin="10">ラジオボタン3</RadioButton>
                <RadioButton Name="btn4" GroupName="buttons" Margin="10">ラジオボタン4</RadioButton>
            </StackPanel>
        </Border>
    </Grid>
</UserControl>
MainWindow.xaml
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:RadioTest" x:Class="RadioTest.MainWindow"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="1*" />
        </Grid.ColumnDefinitions>
        <local:RadioButtonTestControl Grid.Column="0"/>
        <local:RadioButtonTestControl Grid.Column="1" />
        <local:RadioButtonTestControl Grid.Column="2" />
    </Grid>
</Window>

この時、ラジオボタンはUserControl単位でグルーピングされることを期待すると思うのですが(少なくとも私はそうでした)、実際に動かしてみるとUserControl単位ではなくWindow単位で行われるようで、複数配置されたコントロールのラジオボタンすべてが一つのグループにまとめられてしまいます。

UserControl毎にグルーピングを行うためにには、インスタンス毎に異なるGroupNameを指定する必要があります。GroupName名を指定するプロパティをコントロールに追加するか、もっと単純な方法としては以下のように

RadioButtonTestControl.xaml.cs
public partial class RadioButtonTestControl : UserControl
{
    public RadioButtonTestControl()
    {
        InitializeComponent();

        string guid = Guid.NewGuid().ToString();
        btn1.GroupName = guid;
        btn2.GroupName = guid;
        btn3.GroupName = guid;
        btn4.GroupName = guid;
    }
}

コントロールのコンストラクタでGUIDを取得し、ラジオボタンのGroupNameに設定してやるといいようです。

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8