Reputation: 1011
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..
Upvotes: 1
Views: 6845
Reputation: 421
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;
}
}
}
Upvotes: 3