I have a simple UserControl that contains a TextBox and a Button. I would like that clicking the button will create a new user control that will be positioned right after (below) the one That its button was clicked.
For example:
This is the code for the UserControl:
<UserControl x:Class="LearnWPF.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=".9*"/>
<RowDefinition Height=".1*"/>
</Grid.RowDefinitions>
<TextBox ></TextBox>
<Button Grid.Row="1" Content="Create New UserControl" FontSize="20"/>
</Grid>
This is the main window:
<Window x:Class="LearnWPF.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:myUserControl="clr-namespace:LearnWPF"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<myUserControl:MyUserControl />
</StackPanel>
</Window>
I did succeed to add new "myUserControls" to the StackPanel in the main window by doing as advised here. The 2 main problems with this implementation were:
- I Couldn't figure from which "myUserControl" I got the event.
- Even if I did know which button was click and by that where to create the new UserControl, I didn't know how to insert in the middle of the StackPanel (maybe a different panel is needed?)
Also, this solution used code behind. Is there a way to do all that in MVVM?