If you want to add controls to the container, try using Canvas. You could refer to the demo below . Please ask if you have any questions.
MainWindow.xaml:
<StackPanel Orientation="Horizontal">
<StackPanel x:Name="ToolBox" Background="LightGray" Width="100">
<Label Width="50" Height="30" Content="Button" MouseDown="Label_MouseDown"/>
<Label Width="50" Height="30" Content="TextBox" MouseDown="Label_MouseDown"/>
</StackPanel>
<Canvas Name="Container" Background="AliceBlue" Width="600" MouseDown="Container_MouseDown" Cursor="Cross">
</Canvas>
</StackPanel>
MainWindow.xaml.cs:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace AddControls
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
TextBox tb;
Button btn;
private void Label_MouseDown(object sender, MouseButtonEventArgs e)
{
ContentControl c=e.Source as ContentControl;
if (c != null && c.Content != null)
{
string str = c.Content.ToString();
if (str == "TextBox")
{
tb = new TextBox();
tb.Width = 100;
tb.Height = 30;
tb.Text = "TextBox";
}
else if (str == "Button")
{
btn = new Button();
btn.Width = 100;
btn.Height = 30;
btn.Content = "Button";
}
}
}
private void Container_MouseDown(object sender, MouseButtonEventArgs e)
{
if (tb != null)
{
Canvas.SetLeft(tb, e.GetPosition(Container).X);
Canvas.SetTop(tb, e.GetPosition(Container).Y);
Container.Children.Add(tb);
}
else if(btn!=null)
{
Canvas.SetLeft(btn, e.GetPosition(Container).X);
Canvas.SetTop(btn, e.GetPosition(Container).Y);
Container.Children.Add(btn);
}
}
}
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.