locked
CheckBox Checked event fires twice. Leads to "Element is already the child of another element" error.

    Question

  • I have an event handler attached to a CheckBox Checked event. When I check the box, the event fires twice. The first time, the event handler adds an Image control to a canvas. The second time the event fires, the same Image is added again to the canvas causing an "Element already a child of another element" error. I'm very perplexed by this. It happens even when I check to see if the Image is already a child of the canvas. What is causing the problem and how do I fix it?



    • Edited by davidb353 Saturday, December 14, 2013 8:37 PM
    Saturday, December 14, 2013 5:55 AM

Answers

  • More interesting would be the code where you set the event, but the trick may be finding that entire code path. Double events sound like you may be wiring it up twice. Check in the debugger to make sure that isn't happening.

    If you need more detailed help please share a minimal repro sample on your SkyDrive.

    Saturday, December 14, 2013 10:04 PM
    Owner

All replies

  • It will be great if you can post your code.


    Saturday, December 14, 2013 8:08 AM
  • Here is the code for the checked/unchecked event handlers

    void MainPage::LayerCheckBox_Checked(Object^ sender, RoutedEventArgs^ e)
    {
    	auto cb = safe_cast<CheckBox^>(sender);
    	auto layer = safe_cast<Layer^>(cb->DataContext);
    
    	for (auto tile : layer->m_nonNullTiles)
    	{
    		unsigned int i;
    		if (!canvas->Children->IndexOf(tile->m_image, &i))
    		{
    			double x = tile->DstRect.X;
    			double y = tile->DstRect.Y;
    			canvas->SetLeft(tile->m_image, x);
    			canvas->SetTop(tile->m_image, y);
    			canvas->Children->Append(tile->m_image);
    		}
    	}
    }
    
    
    void MainPage::LayerCheckBox_Unchecked(Object^ sender, RoutedEventArgs^ e)
    {
    	auto cb = safe_cast<CheckBox^>(sender);
    	auto layer = safe_cast<Layer^>(cb->DataContext);
    
    	for (auto tile : layer->m_nonNullTiles)
    	{
    		unsigned int i;
    		if (canvas->Children->IndexOf(tile->m_image, &i))
    		{
    			canvas->Children->RemoveAt(i);
    		}
    	}
    }




    • Edited by davidb353 Saturday, December 14, 2013 8:45 PM
    Saturday, December 14, 2013 8:31 PM
  • More interesting would be the code where you set the event, but the trick may be finding that entire code path. Double events sound like you may be wiring it up twice. Check in the debugger to make sure that isn't happening.

    If you need more detailed help please share a minimal repro sample on your SkyDrive.

    Saturday, December 14, 2013 10:04 PM
    Owner
  • Yes, it turned out that I was binding the listview to a property that was not a dependency property. But I don't understand why that is a problem.
    Friday, December 20, 2013 3:53 PM