3

I have made a userControl consisting a few labels and checkboxes and an "x" button for removing itself when clicked.

Considering that in my WPF application, the user can dynamically put as many of this userControl at runtime as he wants, AND that none of them will have a name attribute to address to, how exactly is it possible to remove a UserControl from the application, by clicking on it's -child- button "x" (i.e. inside the event handler of it's "x" button) ???


I've already looked a thousand places and found these particular two lines of code which DID'NT WORK :

((Grid)button.Parent).Children.Remove(this);
((Button)control.Parent).Content = null;
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Ali
  • 1,152
  • 2
  • 14
  • 33
  • Why didn't `.Remove(this)` work? Did you get an exception? – Rachel Dec 06 '12 at 15:22
  • I don't know why. Actually I couldn't trace the codes related to my UserControl, cuz it's a DLL file. But as far as I know, it might have not been able to find the item through the hierarchy ... :/ – Ali Dec 06 '12 at 17:45

1 Answers1

21

In case your control has been added to any kind of container control (i.e. a class derived from Panel) the following should work:

((Panel)this.Parent).Children.Remove(this);
Clemens
  • 123,504
  • 12
  • 155
  • 268