Add the same with the click event

1

I have in my wpf code a listbox with the name "lstBox" (left invisible), and inside it a listBoxItem with a label and a textbox. Outside the listbox, in the same window I have an "add item" button (clicking would make the listbox visible). I would like every click on this button to create a new listboxItem with the same face as I already created in the wpf code inside lstBox and it is only invisible. Can anyone help me?

<Grid>
    <ListBox
        Name="lstBox"
        Margin="0,191,51,46">
        <ListBoxItem
            Name="lstboxitem"
            HorizontalAlignment="Left"
            Height="78"
            VerticalAlignment="Top"
            Width="167"
            Background="#FFE8B0B0"/>
    </ListBox>
    <Button Margin="664,206,76,396" Click="Button_Click_1" 
            />
</Grid>
    
asked by anonymous 26.07.2016 / 21:51

1 answer

1

I made a scope in Visual Basic so you get an idea:

Sub New()
meuListBox.Items.Add("Meu item fixo!")
End Sub

Dim meuItem = meuListBox.Items(0)

Public Sub buttonClick(sender as Object, e as RoutedEventArgs) Handles button.Click
meuListBox.Visibility = Visibility.Visible
meuListBox.Items.Add(meuItem)
End Sub

I will comment everything here before, so I can clarify some doubts:

  

The Sub New() is the initialization of the class / screen, I used it to add the default item.

     

Zero in meuListBox.Items(0) indicates that we are getting the first item , since the index count starts at 0.

     

When writing meuListBox.Items.Add(meuItem) , we are adding the first item in the list (assuming it already exists).

In meuItem we get the first item in your ListBox, and at the click of the button we add that item. Note that the usual would be to have a class, which is the DataContext of your screen, assigning the ListBox.ItemSource to a property of that class, firing the PropertyChanged to the changes on the screen. Another note is the Margin that you assigned to the button, its Grid should contain rows ( RowDefinition ) and columns ( ColumnDefinition ), thus normalizing or even dispensing with the Margin of the button.

I'll leave some important links below for you to improve your knowledge with WPF:

  • WPF-Tutorial.com
  • Josh Smith On WPF
  • Adam Nathan's WPF Unleashed (if you have a chance to read this book, it's worth it!)
  • Pay close attention to the part where you talk about DataBinding , as it is crucial to developing with WPF.

        
    13.08.2016 / 17:13