Search code examples
c#wpfxaml

RadioButtons Xaml vs C#


I'm new in XAML/WPF and there is something I dont understand.

I don't understand why my 3 radioButtons are bound together when I add them directly in the XAML code, and why they aren't when I add them with C#.

What I mean by "Bound" is that they dont uncheck their selves when I check another one...

<Border Background="#3B3B3B" CornerRadius="10">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="150"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>
                <RowDefinition Height="75"/>
                <RowDefinition/>
            </Grid.RowDefinitions>

            <StackPanel Grid.Row="1" 
                        Grid.Column="0" 
                        Name="CatMenu"
                        CanVerticallyScroll="True">
                <RadioButton/>
                <RadioButton/>
            </StackPanel>
        </Grid>
</Border>
foreach (string folder in folders)
            {
                Border border = new Border();
                RadioButton radioButton = new RadioButton
                {
                    Content = System.IO.Path.GetFileName(folder),
                    Background = Brushes.Transparent,
                    Foreground = Brushes.White,
                    Height = 70,
                    VerticalAlignment = VerticalAlignment.Center
                };

                border.Child = radioButton;
                CatMenu.Children.Add(border);
            }

Solution

  • In XAML, if you put multiple radio buttons inside a container like a StackPanel, the system automatically groups them together. This means that only one radio button in the group can be selected at a time, and selecting one will unselect the others in the same group.

    When you create radio buttons in C# code, you have to manually set the group name if you want them to behave like the ones in XAML. By default, each radio button you create in C# is in its own group, so selecting one won't affect the others.

    To group radio buttons together in C#, you just need to set the GroupName property to the same value for all of them. For example, you could set it to "MyGroup" for all the radio buttons you want to group together.

    That way, when you select one radio button, it will unselect any others in the same group that were previously selected.