Hi,
What Sergey mentioned is completely correct but as I'm very interested in practical solutions here is one solution:
First place a wrap panel in your XAML as here :
<WrapPanel x:Name="wpContainer" VerticalAlignment="Top" Height="100" Width="200" MouseDown="wpContainer_MouseDown"
HorizontalAlignment="Stretch" Background="Yellow"></WrapPanel>
The width and height is for preventing it from collapsing when it has no child.
And place mouse down event handler in related code file:
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(index==wpContainer.Children.Count)
wpContainer.Children.Add(newButton);
}
Change it as you wish to fulfill your needs.
Good Luck.