ListBox Control For Windows 10

Introduction 

 
ListBox presents a list of items the user can select from. ListBox lets users select from a pre-defined list of options presented as a text control. We use a ListBox when you want the options to be visible all the time or when users can select more than one option at a time. ListBox controls are always open, so several items can be displayed without user interaction.
 
In the following demo, we are listing some items using a ListBox from which the user can select and the selected will be shown in a TextBlock shown below and clicking the selected Item once more will also remove it.
 
Step 1
 
Open a blank app and add a ListBox control with some items and a TextBlock control either from the toolbox or by copying the following XAML code into your grid. 
  1. <StackPanel Margin="10,10,0,0">    
  2.     <TextBlock Text="List Box" FontSize="20"></TextBlock>    
  3.     <StackPanel Orientation="Horizontal" Margin="0,20,0,0">    
  4.         <TextBlock Text=" Select your options" VerticalAlignment="Center"></TextBlock>    
  5.         <ListBox Margin="10,0,0,0" Name="myListBox" SelectionMode="Multiple" SelectionChanged="myListBox_SelectionChanged">    
  6.             <ListBoxItem Content="Item 1"></ListBoxItem>    
  7.             <ListBoxItem Content="Item 2"></ListBoxItem>    
  8.             <ListBoxItem Content="Item 3"></ListBoxItem>    
  9.         </ListBox>    
  10.     </StackPanel>    
  11.     <TextBlock Margin="0,10,0,0" Name="selectedItems" Foreground="Green"></TextBlock>    
  12. </StackPanel>    
SelectionMode defines whether to allow Single or Multiple selections.
 
 
Step 2
 
Add the following code to your cs page to handle the event while the selection changes.
  1. private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)    
  2. {    
  3.     var selected = myListBox.Items.Cast<ListBoxItem>()    
  4.         .Where(p => p.IsSelected)    
  5.         .Select(t => t.Content.ToString())    
  6.         .ToArray();    
  7.     
  8.     selectedItems.Text ="The selected items are " + string.Join(", ", selected);    
  9. }     
Step 3
 
Run your application and check yourself.
 
 
 

Summary 

 
In this article, we learned about ListBox Control For Windows 10. 


Similar Articles