C# 如何在WrapPanel中的鼠标点击点中添加控件
我的程序中有一个C# 如何在WrapPanel中的鼠标点击点中添加控件,c#,wpf,wrappanel,C#,Wpf,Wrappanel,我的程序中有一个WrapPanel,一些按钮在运行时添加到它(比如这个站点中添加问题标签的面板)。现在我想在按钮之间单击,并在单击鼠标的位置添加一个新按钮。但我不知道如何获取按钮之间的鼠标位置,或者如何获取鼠标单击之前放置的按钮的子索引 我应该说我必须使用WrapPanel,我不想使用Canvas或其他容器 感谢您的帮助。在鼠标中使用此代码单击包装面板的事件: Button b = new Button(); b.Location = new Point(MousePosition.X-this
WrapPanel
,一些按钮在运行时添加到它(比如这个站点中添加问题标签的面板)。现在我想在按钮之间单击,并在单击鼠标的位置添加一个新按钮。但我不知道如何获取按钮之间的鼠标位置,或者如何获取鼠标单击之前放置的按钮的子索引
我应该说我必须使用WrapPanel
,我不想使用Canvas
或其他容器
感谢您的帮助。在
鼠标中使用此代码单击包装面板的事件
:
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);
}
感谢您的回答,但在wpf中,并没有鼠标单击包装名称和按钮的位置属性。我认为你的代码只适用于WinForms。我以为你在谈论WinForms。因此,请看我的更新我在WrapPanel的MouseDown中编写了这段代码,并在第7行中得到了此异常:“此可视化未连接到PresentationSource”您知道如何在鼠标单击位置获取下一个或上一个按钮的索引吗?如果我找到索引,我的问题就会解决。thanksint index=mybutton.GetCharacterIndexFromPoint(鼠标点,true);