1

我的程序中有一个WrapPanel在运行时添加一些按钮的按钮(例如用于在此站点中添加问题标签的面板)。现在我想在按钮之间单击并在单击鼠标的地方添加一个新按钮。但是我不知道如何在按钮之间获取鼠标位置或如何获取在鼠标单击之前放置的按钮的子索引!

我应该说我必须使用WrapPanel,我不想使用Canvas或其他容器。

谢谢你的帮助..

4

2 回答 2

0

MouseClick如果您遇到以下情况,请使用此代码WrapPanel

Button b = new Button();
b.Location = new Point(MousePosition.X-this.ClientSize.Width, MousePosition.Y-this.ClientSize.Height);
this.Controls.Add(b);

更新 :

Button b = new Button();
b.Location = new Point(MousePosition.X - this.ClientSize.Width, MousePosition.Y - this.ClientSize.Height);
this.WrapPanel1.Controls.Add(b);

更新 2:

Button mybutton = new Button();
        mybutton.Content = "This is wpf button";
        Point mousePoint = this.PointToScreen(Mouse.GetPosition(this));  
        MainWindow win = new MainWindow();  
        win.Left = mousePoint.X;  
        win.Top = mousePoint.Y;
        mybutton.PointToScreen(new Point(win.Left,win.Top));
        wrapPanel1.Children.Add(mybutton);
于 2012-06-25T05:17:56.350 回答
0

这段代码解决了我的问题:

  private void wpContainer_MouseDown(object sender, MouseButtonEventArgs e)
    {
        Button newButton = new Button()
                         {
                             Content= wpContainer.Children.Count,

                             Margin = new Thickness()
                             {
                                 Right = 10,

                                 Left = 10,
                             }
                         };

        var mousePosition = Mouse.GetPosition(wpContainer);

        int index=0;

        foreach (var child in wpContainer.Children)
        {
            Button currentButton = (child as Button);

            if (currentButton==null)
                continue;

            Point buttonPosition = currentButton.TransformToAncestor(wpContainer).Transform(new Point(0, 0));

            if (buttonPosition.X  > mousePosition.X && buttonPosition.Y+currentButton.ActualHeight > mousePosition.Y)
            {
                wpContainer.Children.Insert(index, newButton);

                return;                    
            }

            index++;
        }

        if(wpContainer.Children.Count==0 || index==wpContainer.Children.Count) //no items where detected so add it to the end of the Children
            wpContainer.Children.Add(newButton);
    }
于 2012-06-25T07:58:47.520 回答