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.
Aucun commentaire:
Enregistrer un commentaire