Visual Studio.NET WPF - ListBox Adding Items At Run Time
In the given XAML, MyListBox1 is the name of the listbox control. You can add the items at run time by MyListBox1.Items.Add("");
I have included a text box and a Add button. If you type and click add, it will add the text to the list box given below:
Source Code
<Window x:Class="ListBoxAddItem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="225">
<Grid>
<StackPanel Orientation="Vertical" Margin="0,10,0,0">
<TabPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBox Name="TextBox1" Width="100" ></TextBox>
<Button Click="Button_Click" Content="Add" Width="50"></Button>
</TabPanel>
<ListBox Name="MyListBox1" Height="100" HorizontalAlignment="Center" Margin="5,10,5,0" VerticalAlignment="Top" Width="150">
<ListBoxItem Content="India"> </ListBoxItem>
<ListBoxItem Content="USA"></ListBoxItem>
<ListBoxItem Content="UK"></ListBoxItem>
<ListBoxItem Content="Malaysia"></ListBoxItem>
<ListBoxItem Content="Singapore"></ListBoxItem>
</ListBox>
</StackPanel>
</Grid>
</Window>
namespace ListBoxAddItem
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MyListBox1.Items.Add(TextBox1.Text);
}
}
}
|