dimanche 12 janvier 2020

How to have a parent check box that controls child checkbox UWP c#

I have this in my uwp program:

enter image description here

I want it so that:

  • If the parent check box is checked all children are too.
  • If the parent check box is unchecked all children are too.
  • If all the children check boxes are checked the parent will also check.
  • If any of the children check boxes are not checked then the parent wont be checked.

My current code can handle the first three however when I un-check one of the children the unchecked operation for the parent is activated and this un-checks all the children.

The check boxes are bounded to bool items of the same name.

Checked Code:

private void IsChecked(object sender, RoutedEventArgs e)
{
    CheckBox checkBox = sender as CheckBox;

    if (checkBox.Name == "chkWeekday")
    {
        Monday = true;
        Tuesday = true;
        Wednesday = true;
        Thursday = true;
        Friday = true;
    }
    else
    {
        switch (checkBox.Name) // Handles data not updating yet
        {
            case "chkMonday":
                Monday = true;
                break;
            case "chkTuesday":
                Tuesday = true;
                break;
            case "chkWednesday":
                Wednesday = true;
                break;
            case "chkThursday":
                Thursday = true;
                break;
            case "chkFriday":
                Friday = true;
                break;
        }
        if (Monday && Tuesday && Wednesday && Thursday && Friday)
        {
            Weekday = true;
        }
        break;
    }
}

Un-check Code:

private void IsUnchecked(object sender, RoutedEventArgs e)
{
    CheckBox checkBox = sender as CheckBox;

    if (checkBox.Name == "chkWeekday")
    {
        Monday = false;
        Tuesday = false;
        Wednesday = false;
        Thursday = false;
        Friday = false;
    }
    else
    {
        Weekday = false; //<============================================ This is why it un-checks all
        switch (checkBox.Name) // Handles data not updating yet
        {
            case "chkMonday":
                Monday = false;
                break;
            case "chkTuesday":
                Tuesday = false;
                break;
            case "chkWednesday":
                Wednesday = false;
                break;
            case "chkThursday":
                Thursday = false;
                break;
            case "chkFriday":
                Friday = false;
                break;
        }
        break;
    }
}

Is there a way to do this more efficiently / in a way that work.




Aucun commentaire:

Enregistrer un commentaire