Windows Presentation Foundation C#

Creating a WPF Listbox

This C# program demonstrates how to create a simple listbox and a handle a selection event in a WPF program.

MainWindow.xaml

<Window x:Class="ListBox1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="XoaX.net" Height="350" Width="525">
    <Grid>
        <Label Content="Apostles" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="111"/>
        <ListBox HorizontalAlignment="Left" Height="121" Margin="10,36,0,0" VerticalAlignment="Top" Width="111"
          SelectionChanged="OnSelectionChange">
            <ListBoxItem>Matthew</ListBoxItem>
            <ListBoxItem>Mark</ListBoxItem>
            <ListBoxItem>Luke</ListBoxItem>
            <ListBoxItem>John</ListBoxItem>
            <ListBoxItem>Peter</ListBoxItem>
            <ListBoxItem>Paul</ListBoxItem>
            <ListBoxItem>Thomas</ListBoxItem>
            <ListBoxItem>James</ListBoxItem>
            <ListBoxItem>Judas</ListBoxItem>
        </ListBox>
        <TextBlock Name="qSelectionTB" HorizontalAlignment="Left" Margin="10,162,0,0"
          TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Height="95" Width="111"/>
    </Grid>
</Window>
 

MainWindow.xaml.cs

using System.Windows;
using System.Windows.Controls;

namespace ListBox1 {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
        }
        private void OnSelectionChange(object sender, SelectionChangedEventArgs args) {
            ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);
            qSelectionTB.Text = "You selected " + lbi.Content.ToString() + ".";
        }
    }
}
 

Window with Listbox

Window
 

Window with Selection

Selection
 
 

© 2007–2025 XoaX.net LLC. All rights reserved.