简体   繁体   中英

How to add ListBox Items in WPF?

how do I add items to a listbox control by using < ListBox.ItemTemplate> ?

here is the xaml part:

<ListBox HorizontalAlignment="Stretch" Name="ListBox1" VerticalAlignment="Stretch" Margin="0,20">
 <ListBox.ItemTemplate>
  <DataTemplate>
   <Label Content="???????" />
  </DataTemplate>
 </ListBox.ItemTemplate>
</ListBox>

and here is the code for adding items:

private sub Button1_Click() Handles Button1.Click
ListBox1.Items.Add("Hello World")
End Sub

if I click on the buton1, a list item will be added with "??????" - I need to replace the "?????" with {Binding} or something so it can get the value correct value from button1_click ("Hello World")

Yes, just replace it with {Binding} , that alone should do it.

( {Binding} binds to the DataContext and the DataContext of the ItemTemplate will be the respective item, if the item is a simple string as in your example that will do, if it is a complex data object you will want to specify a Path to bind to a property of the item)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM