title: C# WPF - Completely Remove Object and ALL Children
body: <p>I have a Grid which I am utilizing as a sort of "popup" control. This control is dynamically created for each specific item clicked.</p>
  
  <p>Please note, this control has layers of other controls with children, other grids and stackpanels.</p>
  
  <p>To close it I have a "Cancel" button, currently I am casting the parent object in the EventHandler and using <code>[castedobject].Children.Remove(popup)</code> to close the object.</p>
  
  <p>However, when I click another "parent" when the program goes to re-create the Grid window I am getting lots of Exceptions because the same objects are trying to get re-assigned as children even though they are "currently assigned".</p>
  
  <p>My question is this: What command do I use (when closing) to permanently remove all reciprocal children and their associations? This seems like something that would be standard in a dynamic control environment. I am sure I am missing something simple, but I've tried the methods I have found while searching Stack Overflow and Google, but I'm still reaching the same Exceptions.</p>
  
  <pre><code>colorCancelBtn.Click += delegate (object source, RoutedEventArgs e)
          {
              container.Children.Clear();
              Grid temp = (Grid)dataObject.FindName("colorPicker");
              Grid parent = (Grid)temp.Parent;
              parent.Children.Remove(temp);
              dataObject.UnregisterName("colorPicker");
          };
  </code></pre>