Ali
Ali

Reputation: 1152

How to make a UserControl remove itself at runtime (in WPF)?

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;

Upvotes: 3

Views: 10099

Answers (1)

Clemens
Clemens

Reputation: 128061

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);

Upvotes: 21

Related Questions