如何使用WPF中的上下文菜单删除选定的StackPanel

时间:2018-07-13 08:44:55

标签: c# wpf

我有一个StackPanel,有孩子。 StackPanel个孩子也是StackPanel。子项StackPanel是在运行时动态添加的。我有一个带有删除标题的上下文菜单。当我单击删除菜单时,所选的堆栈子项将被删除。我不知道要使用上下文菜单删除StackPanel子级。请任何人指导我解决此问题。我的示例代码如下,

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

背后的代码

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

我也尝试过这种方法,但是没有被删除。

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

Please refer the screenshot

1 个答案:

答案 0 :(得分:1)

这应该有效:

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