Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » WPF » WPF ListBox

WPF ListBox

This tutorial shows you how to work with the ListBox control available in WPF.

Author Rank :
Page Views : 43272
Downloads : 437
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WPFListBox.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Introduction

The ListBox tag represents a Silverlight ListBox control in XAML.

 

<ListBox></ListBox>

 

The Width and Height properties represent the width and the height of a ListBox.  The Name property represents the name of the control, which is a unique identifier of a control. The Margin property tells the location of a ListBox on the parent control. The HorizontalAlignment and VerticalAlignment properties are used to set horizontal and vertical alignments.

 

The following code snippet sets the name, height, and width of a ListBox control.  The code also sets horizontal alignment to left and vertical alignment to top.

 

<ListBox Margin="10,10,0,13" Name="listBox1" HorizontalAlignment="Left"

                 VerticalAlignment="Top" Width="194" Height="200" />

 

Adding ListBox Items

A ListBox control hosts a collection of ListBoxItem. The following code snippet adds items to a ListBox control.

<ListBox Margin="10,10,0,13" Name="listBox1" HorizontalAlignment="Left"

         VerticalAlignment="Top" Width="194" Height="200">

    <ListBoxItem Content="Coffie"></ListBoxItem>

    <ListBoxItem Content="Tea"></ListBoxItem>

    <ListBoxItem Content="Orange Juice"></ListBoxItem>

    <ListBoxItem Content="Milk"></ListBoxItem>

    <ListBoxItem Content="Iced Tea"></ListBoxItem>

    <ListBoxItem Content="Mango Shake"></ListBoxItem>

</ListBox>

The above code generates Figure 1.

ListBoxImg1.jpg 

Figure 1. ListBox with items

Adding ListBox Items Dynamically

In the previous section, we saw how to add items to a ListBox at design-time from XAML. We can add items to a ListBox from the code.  

Let's change our UI and add a TextBox and a button control to the page. The XAML code for the TextBox and Button controls look like following:

<TextBox Height="23" HorizontalAlignment="Left" Margin="8,14,0,0"

                 Name="textBox1" VerticalAlignment="Top" Width="127" />

<Button Height="23" Margin="140,14,0,0" Name="button1" VerticalAlignment="Top"

                HorizontalAlignment="Left" Width="76" Click="button1_Click">

            Add Item

</Button>

The final UI looks like Figure 2.

ListBoxImg2.jpg 

Figure 2.

On button click event handler, we add the content of TextBox to the ListBox by calling ListBox.Items.Add method. The following code adds TextBox contents to the ListBox items.

private void button1_Click(object sender, RoutedEventArgs e)

{

    listBox1.Items.Add(textBox1.Text);

}

On button click event handler, we add the content of TextBox to the ListBox by calling ListBox.Items.Add method.

Now if you enter text in the TextBox and click Add Item button, it will add contents of the TextBox to the ListBox.

ListBoxImg3.jpg 

Figure 3. Adding ListBox items dynamically

Deleting ListBox Items

We can use ListBox.Items.Remove or ListBox.Items.RemoveAt method to delete an item from the collection of items in the ListBox. The RemoveAt method takes the index of the item in the collection.

Now, we modify our application and add a new button called Delete Item. The XAML code for this button looks like below.

<Button Height="23" Margin="226,14,124,0" Name="DeleteButton"

        VerticalAlignment="Top" Click="DeleteButton_Click">

    Delete Item</Button>

The button click event handler looks like following. On this button click, we find the index of the selected item and call ListBox.Items.RemoveAt method as following.

 

private void DeleteButton_Click(object sender, RoutedEventArgs e)

{

   listBox1.Items.RemoveAt

       (listBox1.Items.IndexOf(listBox1.SelectedItem));                 

}

 

Formatting and Styling

Formatting ListBox Items

The Foreground and Background attributes of ListBoxItem represents the background and foreground colors of the item. The following code snippet sets background and foreground color of a ListBoxItem.

<ListBoxItem Background="LightCoral" Foreground="Red" Content="Coffie"></ListBoxItem>

 

The FontFamily, FontSize, and FontWeight are used to set a font of a ListBoxItem. The following code snippet sets font verdana, size 12, and bold of a ListBoxItem.

<ListBoxItem Background="LightCoral" Foreground="Red" Content="Coffie"

                         FontFamily="Verdana" FontSize="12" FontWeight="Bold"></ListBoxItem>

I set the following properties of ListBoxItems.

<ListBoxItem Background="LightCoral" Foreground="Red" Content="Coffie"

                         FontFamily="Verdana" FontSize="12" FontWeight="Bold"></ListBoxItem>

            <ListBoxItem Background="LightGray" Foreground="Black" Content="Tea"

                         FontFamily="Georgia" FontSize="14" FontWeight="Bold"></ListBoxItem>

            <ListBoxItem Background="LightBlue" Foreground="Purple" Content="Orange Juice"

                         FontFamily="Verdana" FontSize="12" FontWeight="Bold"></ListBoxItem>

            <ListBoxItem Background="LightGreen" Foreground="Green" Content="Milk"

                         FontFamily="Georgia" FontSize="14" FontWeight="Bold"></ListBoxItem>

            <ListBoxItem Background="LightBlue" Foreground="Blue" Content="Iced Tea"

                         FontFamily="Verdana" FontSize="12" FontWeight="Bold"></ListBoxItem>

            <ListBoxItem Background="LightSlateGray" Foreground="Orange" Content="Mango Shake"

                         FontFamily="Georgia" FontSize="14" FontWeight="Bold"></ListBoxItem>

The new ListBox looks like Figure 4.

 

ListBoxImg4.jpg 

Figure 4. Formatted ListBox

Displaying Images in a ListBox

We can put any controls inside a ListBoxItem such as an image and text. To display an image side by side some text, I simply put an Image and TextBlock control within a StackPanel. The Image.Source property takes the name of the image you would like to display in the Image control and TextBlock.Text property takes a string that you would like to display in the TextBlock.

The following code snippet adds an image and text to a ListBoxItem.

<ListBoxItem Background="LightCoral" Foreground="Red"

             FontFamily="Verdana" FontSize="12" FontWeight="Bold">

    <StackPanel Orientation="Horizontal">

        <Image Source="coffie.jpg" Height="30"></Image>

        <TextBlock Text="Coffie"></TextBlock>

    </StackPanel>

</ListBoxItem>

 

After changing my code for all 5 ListBoxItems, the ListBox looks like Figure 5.

ListBoxImg5.jpg
Figure 5.  ListBoxItems with Image and text

ListBox with CheckBoxes

If you put a CheckBox control inside ListBoxItems, you generate a ListBox control with checkboxes in it. The CheckBox can host controls within it as well. For instance, we can put an image and text block as content of a CheckBox.

The following code snippet adds a CheckBox with an image and text to a ListBoxItem.

<ListBoxItem Background="LightCoral" Foreground="Red"

             FontFamily="Verdana" FontSize="12" FontWeight="Bold">               

        <CheckBox Name="CoffieCheckBox">

            <StackPanel Orientation="Horizontal">

            <Image Source="coffie.jpg" Height="30"></Image>

            <TextBlock Text="Coffie"></TextBlock>

        </StackPanel>

    </CheckBox>

</ListBoxItem>

 

I change the code of ListBoxItems and add following CheckBoxes to the items. As you may see, I have set the name of the CheckBoxes using Name property. If you need to access these CheckBoxes, you may access them in the code using their Name property.

 <ListBoxItem Background="LightCoral" Foreground="Red"

             FontFamily="Verdana" FontSize="12" FontWeight="Bold">               

        <CheckBox Name="CoffieCheckBox">

            <StackPanel Orientation="Horizontal">

            <Image Source="coffie.jpg" Height="30"></Image>

            <TextBlock Text="Coffie"></TextBlock>

        </StackPanel>

    </CheckBox>

</ListBoxItem>

<ListBoxItem Background="LightGray" Foreground="Black"

             FontFamily="Georgia" FontSize="14" FontWeight="Bold">

    <CheckBox Name="TeaCheckBox">

        <StackPanel Orientation="Horizontal">

            <Image Source="tea.jpg" Height="30"></Image>

            <TextBlock Text="Tea"></TextBlock>

        </StackPanel>

    </CheckBox>

</ListBoxItem>

<ListBoxItem Background="LightBlue" Foreground="Purple"

             FontFamily="Verdana" FontSize="12" FontWeight="Bold">

    <CheckBox Name="OrangeJuiceCheckBox">

        <StackPanel Orientation="Horizontal">

            <Image Source="OrangeJuice.jpg" Height="40"></Image>

            <TextBlock Text="OrangeJuice"></TextBlock>

        </StackPanel>

    </CheckBox>

</ListBoxItem>

<ListBoxItem Background="LightGreen" Foreground="Green"

             FontFamily="Georgia" FontSize="14" FontWeight="Bold">

    <CheckBox Name="MilkCheckBox">

        <StackPanel Orientation="Horizontal">

            <Image Source="Milk.jpg" Height="30"></Image>

            <TextBlock Text="Milk"></TextBlock>

        </StackPanel>

    </CheckBox>

</ListBoxItem>

<ListBoxItem Background="LightBlue" Foreground="Blue"

             FontFamily="Verdana" FontSize="12" FontWeight="Bold">

    <CheckBox Name="IcedTeaCheckBox">

        <StackPanel Orientation="Horizontal">

            <Image Source="IcedTea.jpg" Height="30"></Image>

            <TextBlock Text="Iced Tea"></TextBlock>

        </StackPanel>

    </CheckBox>

</ListBoxItem>

<ListBoxItem Background="LightSlateGray" Foreground="Orange"

             FontFamily="Georgia" FontSize="14" FontWeight="Bold">

    <CheckBox Name="MangoShakeCheckBox">

        <StackPanel Orientation="Horizontal">

            <Image Source="MangoShake.jpg" Height="30"></Image>

            <TextBlock Text="Mango Shake"></TextBlock>

        </StackPanel>

    </CheckBox>

</ListBoxItem>

 

Now, the new ListBox looks like Figure 6.

 

ListBoxImg6.jpg 

Figure 6. ListBox with CheckBoxes

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 Article Extensions
Contents added by Mahesh Chand on May 01, 2009

Testing community content addition. Wiki style.

 

 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Check Boxes and Focus by computerart On October 1, 2008
I noticed that when you click the check boxes in the ListBox, that the corresponding ListBoxItems are not "selected". How would you accomplish something like that? Great article, by the way. Very helpful to those of us new to WPF.
Reply | Email | Modify 
Re: Check Boxes and Focus by Mahesh On April 7, 2009
It is because they are two different controls. One way to do is, select text in your code when check box is checked.
Reply | Email | Modify 
delete from data binding by Manu On April 16, 2009
What if the listbox is tied to a database. How would i be able to delete each one thereafter. I am able to pass them but I get a string to char conversion error.
Reply | Email | Modify 
Re: delete from data binding by Mahesh On May 1, 2009
How are you binding the control? You must be using ItemsSource? just set ItemsSource property to null.
Reply | Email | Modify 
some issue by sachin On May 29, 2009
i want to add images in listbox when i click any directory at runtime from my application add all images in listbox horizontally.when there are no space for image in that row then all remaining image are add in next row.and also show the name of image in the bottom of image alogwith a checkbox.
Reply | Email | Modify 
sdsdsd by amol On June 22, 2009
sdsdsdsdsd
Reply | Email | Modify 
Check All Option by Mike On February 26, 2010

I have use this to populate a list view that has data from an SQL DB with a check box for each line.  I would like to have an option to "Check All'.   This would change all the checkboxes from unchecked to checked an vice-versa.  Can you post how to do this.

Thanks,
M

Reply | Email | Modify 
Brilliant!! by rav On August 5, 2011
It is very good article!
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.