checkbox like radiobutton wpf c#

感情迁移 提交于 2019-12-02 08:18:44

问题


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">
            </StackPanel>

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;
                companiesContainer.Children.Add(ch);
            }
        }

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..


回答1:


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()
    {
        InitializeComponent();
        this.Loaded += MainWindow_Loaded;
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        CreateCheckboxes();
    }

    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
            checkboxcontainer.Children.Add(c);
        }
    }

    // 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;
            }
        }
    }


来源:https://stackoverflow.com/questions/17320456/checkbox-like-radiobutton-wpf-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!