C# – Prevent CheckBox Checked event from firing

cwpf

I have some CheckBoxes created dynamically on code. I do read a barcode using a barcode reader. I'm trying to stop the Unchecked and Checked events from firing when I'm using the barcode. For that effect I:

  1. only assign both events when I get the focus on the Checkboxes, and when I lose the focus I take the events out.
  2. after each Checked and Unchecked event I assign the focus to another control in the window (so the LostFocus event gets triggered)

But went I use the barcode reader, all of the CheckBoxes objects receive the Unchecked event if they were checked (but not the Checked event if they were unchecked).

Is there a way to prevent this from happening?

The only places where the Unchecked method is being used are the ones in the code show, nowhere else in the code of the application.

A pointer to a better way to handle this dynamic creation of Checkboxes will not go unappreciated.

private void SomeMethod ()
{
  foreach (KeyValuePair<String, String> kvp in someDictionary)
  {
    CheckBox checkBox = new CheckBox();
    checkBox.Content = kvp.Key;
    checkBox.GotFocus +=new RoutedEventHandler(checkBox_GotFocus);
    checkBox.LostFocus += new RoutedEventHandler(checkBox_LostFocus);
    checkBox.ClickMode = ClickMode.Release;
    Grid.SetRow(checkBox, fileSelectionGrid.RowDefinitions.Count);
    fileSelectionGrid.Children.Add(checkBox);
    RowDefinition row = new RowDefinition();
    fileSelectionGrid.RowDefinitions.Add(row);
  }
}

void checkBox_LostFocus(object sender, RoutedEventArgs e)
{
  CheckBox checkBox = sender as CheckBox;
  checkBox.Checked -= new RoutedEventHandler(checkBox_Checked);
  checkBox.Unchecked -= new RoutedEventHandler(checkBox_Unchecked);
}

void checkBox_GotFocus(object sender, RoutedEventArgs e)
{
  CheckBox checkBox = sender as CheckBox;
  checkBox.Checked += new RoutedEventHandler(checkBox_Checked);
  checkBox.Unchecked += new RoutedEventHandler(checkBox_Unchecked);
}

EDIT :

Just checked that the click event is not raised when the CheckBox doesn't have the focus.

Best Answer

Usually for such kind of problems i declare a bool flag which is assigned value before and after code line where an event will fire and when that event is fired the first thing it does is to check for that flag value.

For e.g.

bool flag = false;

private void SomeMethod()
{
  flag = true;
  YourCheckBox.checked = false;
  flag = false;
}

void YourCheckBox_Checked(object sender, RoutedEventArgs e)
{
  if (flag)
     return;

  // Do something....
}

void YourCheckBox_UnChecked(object sender, RoutedEventArgs e)
{
  if (flag)
     return;

  // Do something....
}

When i assigned flag = true the next line will fire selection changed event. when i does it will return coz flag is set to true;

Related Topic