开发者

WPF: Removing "yourself" from the parent container

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 Messa开发者_如何学CgeBox.Show("Are you sure [...]
}

Is it normal to do it this way in WPF?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜