Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Removing "yourself" from the parent container

Tags:

c#

wpf

I have a button in my user control which should be used to remove the user control from its parent container. This is the way I have coded it today.

private void RemoveRoleButton_Click(object sender, RoutedEventArgs e)
{
    if (ConfirmRoleRemoval())
    {
        Panel parentPanel = (Panel)this.Parent;
        parentPanel.Children.Remove(this);
    }
}

private bool ConfirmRoleRemoval()
{
    return MessageBox.Show("Are you sure [...]
}

Is it normal to do it this way in WPF?

like image 469
Deniz Dogan Avatar asked Jan 28 '10 09:01

Deniz Dogan


1 Answers

Yes, it looks fine to me. As Mike Hillberg writes in his blog:

An element doesn’t actually pick its logical parent; instead, a parent “adopts” children.

Thus, it makes sense that "removing" a child is also done through the object model of the parent.

As a side note: You might want to consider throwing a "nice" exception (or even disabling the button) when the parent is not a Panel (rather than waiting for the InvalidCastException).

like image 90
Heinzi Avatar answered Sep 27 '22 23:09

Heinzi