I'm trying to dynamically add items to the StackPanel.

<StackPanel Name="Panel1" Grid.Column="1" Grid.Row="2" HorizontalAlignment="Left" Height="auto" Margin="0,41,0,0" VerticalAlignment="Top" Width="auto"> </StackPanel> 

Here is the class where I'm trying to add:

 public class DynamicCreator { MainWindow main = new MainWindow(); public void TextBoxCreator(int n) { for (int i = 0; i < n; i++) { main.Panel1.Children.Add(new Label { Content = "Test" }); } main.UpdateLayout(); } } 

But the elements do not appear. What to do? Where is the mistake?

  • ... do you like this code yourself? - Ev_Hyper
  • one
    @Ev_Hyper, I ask a question here, because I need help, if you don’t like my code, please do not minus, but write where the error is and how to fix it. I'll be very grateful. - Nikita
  • I will be happy to help you if you write what you want to do - Ev_Hyper
  • I want to add an nn Label to the StackPanel at the touch of a button. For this, I made a separate class, where there is a TextBoxCreator method, which should use the loop to add these elements. If I do the same from MainWindow.xaml.cs , then everything works, but I want to understand how to add elements to the MainWindow from another class. - Nikita
  • look you are going the wrong way, work with data and not with controls. Based on your description, you just want to display a certain collection of data that can change, in particular, when you click on the button, elements are added. There is a standard solution - ObservableCollection , a collection that reports its change. - Ev_Hyper

2 answers 2

Keep your Label somewhere in ObservableCollection :

 public ObservableCollection<Label> myLabels { get; set; } = new ObservableCollection<Label>(); 

Snap:

 <ItemsControl Width="Auto" Height="Auto" ItemsSource="{Binding myLabels}"></ItemsControl> 

Add the Label you need in the code:

 myLabels.Add(...); 

PS: do not forget about DataContext : DataContext = this .

  • one
    I wonder for what reason your answer received a minus - user227049
  • @FoggyFinder, someone probably didn’t like the answer. - Ares
  • It seems that it is not the first time when I notice when good answers are received - no apparent reason and without comment. - user227049

I think you add the wrong window. Do not create a new instance of MainWindow; take an existing one.

  • Thanks for the answer, but I did not quite understand. How to take an existing copy? - Nikita
  • @Nikita, how do you call this method? You can not pass a link to the window (this)? - Andrey NOP
  • @Nikita: Well, as a programmer, you need to ask where in your program you can get a link to the main window. - VladD