Share via


How to: Create a ListBox with an Event Handler

This example shows how to create a ListBox using the Extensible Application Markup Language (XAML) and implement event handlers in C# or Microsoft Visual Basic to handle selection changes.

The ListBox in the following XAML example contains multiple list items. When the user selects one of the items, the event handler displays the name of the selected item in the TextBox.

Example

<TextBox Name="tb" Width="140" Height="30"></TextBox>   
<ListBox Name="lb" Width="100" Height="55" SelectionChanged="PrintText" SelectionMode="Single">
      <ListBoxItem>Item 1</ListBoxItem>
      <ListBoxItem>Item 2</ListBoxItem>
      <ListBoxItem>Item 3</ListBoxItem>
      <ListBoxItem>Item 4</ListBoxItem>
      <ListBoxItem>Item 5</ListBoxItem>
      <ListBoxItem>Item 6</ListBoxItem>
      <ListBoxItem>Item 7</ListBoxItem>
      <ListBoxItem>Item 8</ListBoxItem>
      <ListBoxItem>Item 9</ListBoxItem>
      <ListBoxItem>Item 10</ListBoxItem>
</ListBox>
void PrintText(object sender, SelectionChangedEventArgs args)
{
  ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);
  tb.Text = "   You selected " + lbi.Content.ToString() + ".";
}
Sub PrintText(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)

    Dim lbsender As ListBox
    Dim li As ListBoxItem

    lbsender = CType(sender, ListBox)
    li = CType(lbsender.SelectedItem, ListBoxItem)
    tb.Text = "   You selected " & li.Content.ToString & "."
End Sub

For the complete sample see: List Box Sample.

See Also

Tasks

How to: Create a Horizontal ListBox

Reference

ListBoxItem

Concepts

ListBox Overview