Reputation: 1616
I'm dynamically creating a list of CheckBoxes in code behind. This was working fine but I then wanted to add in an initial [Select All] checkbox.
This is how I am creating the checkboxes;
var splCheckBoxes = new StackPanel();
var ckb = new CheckBox
{
Content = "[Select All]",
Margin = new Thickness(40, 0, 0, 0),
IsChecked = true
};
ckb.Checked += CkbSelectAllChecked;
ckb.Unchecked += CkbSelectAllChecked;
splCheckBoxes.Children.Add(ckb);
var distinctValues = [LIST OF VALUES TO POPULATE INTO CHECKBOXES];
foreach (var distinctValue in distinctValues)
{
ckb = new CheckBox
{
Content = distinctValue,
Margin = new Thickness(40, 0, 0, 0)
};
if (string.IsNullOrEmpty(distinctValue))
ckb.Content = "[BLANK]";
ckb.IsChecked = true;
ckb.Checked += CkbOnChecked;
ckb.Unchecked += CkbOnChecked;
splCheckBoxes.Children.Add(ckb);
}
And here is the event handlers;
private void CkbOnChecked(object sender, RoutedEventArgs routedEventArgs)
{
var senderCbx = ((CheckBox)sender);
if (!senderCbx.IsChecked.Value)
{
var selectAllCbx = ((StackPanel)senderCbx.Parent).Children.OfType<CheckBox>().FirstOrDefault(x => x.Content.ToString() == "[Select All]");
selectAllCbx.IsChecked = false;
}
...DoProcessingBasedOnUpdatedCheckboxes();
}
private void CkbSelectAllChecked(object sender, RoutedEventArgs routedEventArgs)
{
var senderCbx = ((CheckBox)sender);
var checkBoxes = ((StackPanel)senderCbx.Parent).Children.OfType<CheckBox>();
checkBoxes = checkBoxes as CheckBox[] ?? checkBoxes.ToArray();
var willCheck = checkBoxes.FirstOrDefault().IsChecked.Value;
foreach (var checkBox in checkBoxes)
{
if (checkBox.Content.ToString() != "[Select All]")
checkBox.IsChecked = willCheck;
}
}
I believe I could do this by only running DoProcessingBasedOnUpdatedCheckboxes
when a bool is set to true after the CkbSelectAllChecked
is completed, but I think the way I'm going about this is a bit long winded. Any recommendations for a better way to achieve this? Perhaps without having the Event Handlers kicking off so many unnecessary times.
The behaviour I'm looking for is the same as how it functions in the example here.
Upvotes: 0
Views: 59
Reputation: 3950
Consider using the on mouse up event instead of the on checked/on unchecked events.
The on checked and unchecked events are going to be fired every time the checkbox's "is checked" value changes...regardless of whether the user initiated the change or if the change was done through another event (like the check all checkbox automatically changed the value).
If you use the mouse up event instead you won't be unnecessarily executing this code.
Upvotes: 1
Reputation: 4164
Since it is WPF, you can try :
While creating special check boxes, you can also define binding for checked property with main check box so that when it is checked/unchecked - respective child check boxes will reflect same.
Upvotes: 0