Add the same with the click event

Asked

Viewed 196 times

1

I have in my wpf code a listbox with the name "lstBox" (I left it invisible), and inside it a listBoxItem with a label and a textbox . Outside the listbox , in the same window I have a button " add item " (when clicking would be visible the listbox). I would like every click on this button to create a new listboxItem with the same face as I already created in wpf code inside lstBox and this just invisible. Can someone 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>
  • Could post an excerpt of the code used for a larger view of the problem?

  • I edited the question by also posting the shamanic code that I have made. Need that when clicking the button with the click event, my listbox has more a listboxitem exactly like the one I have already created in the shampoo

1 answer

1

I made a scope in Visual Basic to give you 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 on 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 taking 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 of your Listbox, and at the click of the button we add this item. Note that the usual would be to have a class, being it the DataContextof your screen, assigning the ListBox.ItemSource to a property of this class, firing the PropertyChanged for changes on the screen. Another observation is Margin that you assigned to the button, your Grid should contain lines (RowDefinition) and columns (ColumnDefinition), thus normalizing or even dispensing with the Margin button.

I will leave below some important links for you to perfect your knowledge with WPF:

  1. WPF-Tutorial.com
  2. Josh Smith On WPF
  3. WPF Unleashed by Adam Nathan (if you get a chance to read that book, it’s worth it!)

Pay close attention to the part where you talk about DataBinding, because it is crucial to development with WPF.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.