Yogeshwaran
Yogeshwaran

Reputation: 170

How to remove selected stackpanel using context menu in wpf

I have a StackPanel with children. The StackPanel children are also StackPanel. Children StackPanel is added by dynamically at runtime. I have a context menu with delete header. When I click the delete menu the selected stack children will be deleted. I don't have any idea to remove the StackPanel children by using the context menu. Please, anyone, guide me to resolve this. My sample code is as below,

<StackPanel x:Name="mainPanel" Background="#F0F0F0">
        <StackPanel.ContextMenu>
            <ContextMenu>
                <MenuItem Click="ParentContextMenu_Click" Header="Add Stackpanel" />
            </ContextMenu>
        </StackPanel.ContextMenu>
    </StackPanel>

Code behind

 public partial class MainView : Window
    {
        ContextMenu contextMenu;
        MenuItem menuItem;
        public MainView()
        {
            InitializeComponent();
            contextMenu = new ContextMenu();
            menuItem = new MenuItem();
            menuItem.Header = "Delete Panel";
            menuItem.Click += ChildContextMenu_Click;
            contextMenu.Items.Add(menuItem);
        }

        private void ChildContextMenu_Click(object sender, RoutedEventArgs e)
        {

        }

        private void ParentContextMenu_Click(object sender, RoutedEventArgs e)
        {
            StackPanel stack = new StackPanel()
            {
                Name = "childStack"
                Height = 100,
                Width = 100,
                Background = Brushes.White,
                Margin = new Thickness(15, 15, 0, 10),
                ContextMenu = contextMenu
            };

            mainPanel.Children.Add(stack);
        }
    }

I have tried like this also, but is not deleted.

mainPanel.Children.Remove((StackPanel)this.FindName("childStack"));

Please refer the screenshot

Upvotes: 1

Views: 728

Answers (1)

mm8
mm8

Reputation: 169270

This should work:

private void ChildContextMenu_Click(object sender, RoutedEventArgs e)
{
    MenuItem mi = sender as MenuItem;
    if (mi != null)
    {
        ContextMenu cm = mi.Parent as ContextMenu;
        if (cm != null)
        {
            StackPanel sp = cm.PlacementTarget as StackPanel;
            if (sp != null)
            {
                Panel parentSp = sp.Parent as Panel;
                if (parentSp != null)
                    parentSp.Children.Remove(sp);
            }
        }
    }
}

Upvotes: 1

Related Questions