Home > DeveloperSection > Forums > checkbox like radiobutton wpf c#
Hank Greenberg
Hank Greenberg

Total Post:12

Posted on    July-18-2013 2:06 AM


 1 Reply(s)
 2316  View(s)
Rate this:
HI developers!

i have investigated this problem but this is solved in design view and code-behind. but my problem is little difference: i try to do this as only code-behind because my checkboxes are dynamically created according to database data.In other words, number of my checkboxes is not stable. i want to check only one checkbox in group of checkboxes. when i clicked one checkbox,i want that ischecked property of other checkboxes become false.this is same property in radiobuttons. i take my checkboxes from a stackpanel in xaml side:

<StackPanel Margin="4" Orientation="Vertical"  Grid.Row="1" Grid.Column="1" Name="companiesContainer">


my xaml.cs:

using (var c = new RSPDbContext())


            var q = (from v in c.Companies select v).ToList();

            foreach (var na in q)


                CheckBox ch = new CheckBox();

                ch.Content = na.Name;

                ch.Tag = na;




foreach (object i in companiesContainer.Children)


                CheckBox chk = (CheckBox)i;

                chk.SetBinding(ToggleButton.IsCheckedProperty, "DataItem.IsChecked");


how can i provide this property in checkboxes in xaml.cs ? 

thanks in advance..

shreesh chandra shukla
shreesh chandra shukla

Total Post:105

Posted on    July-18-2013 2:43 AM


Add an an event handler for the checked event. When creating the checkbox, add this (same) event handler to each checkbox.

In the event handler, run through each checkbox you've added, and for every checkbox, uncheck it UNLESS it's the same checkbox as the sender.

That I think should do the trick (off the top of my head).

Here is some code I just knocked up that should help:

XAML part is just a stack panel called: Name="checkboxcontainer"

Codebehind part:

    public MainWindow()



        this.Loaded += MainWindow_Loaded;


    private void MainWindow_Loaded(object sender, RoutedEventArgs e)




    private void CreateCheckboxes()


        for (int i = 0; i <= 5; i++)


            CheckBox c = new CheckBox();

            c.Name = "Check" + i.ToString();

            c.Checked += c_Checked; //This is adding the event handler to the checkbox




    // This is the event handler for the checkbox

    private void c_Checked(object sender, RoutedEventArgs e)


        foreach (var control in checkboxcontainer.Children)


            if (control is CheckBox && control != sender)


                CheckBox cb = (CheckBox)control;

                cb.IsChecked = false;



Don't want to miss updates? Please click the below button!

Follow MindStick