【发布时间】:2012-06-24 19:07:16
【问题描述】:
我的程序中有一个WrapPanel,它在运行时添加了一些按钮(例如在此站点中添加问题标签的面板)。现在我想在按钮之间单击并在鼠标单击的地方添加一个新按钮。但我不知道如何在按钮之间获取鼠标位置或如何获取在鼠标单击之前放置的按钮的子索引!
我应该说我必须使用WrapPanel,我不想使用Canvas 或其他容器。
感谢您的帮助..
【问题讨论】:
我的程序中有一个WrapPanel,它在运行时添加了一些按钮(例如在此站点中添加问题标签的面板)。现在我想在按钮之间单击并在鼠标单击的地方添加一个新按钮。但我不知道如何在按钮之间获取鼠标位置或如何获取在鼠标单击之前放置的按钮的子索引!
我应该说我必须使用WrapPanel,我不想使用Canvas 或其他容器。
感谢您的帮助..
【问题讨论】:
在WrapPanel 的MouseClick 事件中使用此代码:
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);
【讨论】:
这段代码解决了我的问题:
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);
}
【讨论】: