top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to Bind a Dictionary to a Listbox in Apps Based in XAML

+3 votes
568 views
 

Introduction

The purpose of this sample is to show how to bind a Dictionary a Lisbox in apps based in XAML, using the MVVM pattern.

Building the Sample

You only need Visual Studio 2012/2013 running in Windows 7, 8, 8.1 or later.

Description

Suppose we have a resource dictionary with some data that we need to show in an application and for each item in a Listbox, we want to show the key/value.

We will start by creating a model class called "Company" that has only two properties: Name and URL.
C#
/// <summary>   
/// Define the Company.   
/// </summary>   
public class Company   
{   
    /// <summary>   
    /// Gets or sets the name.   
    /// </summary>   
    /// <value>The name.</value>   
    public string Name { get; set; }   
  
    /// <summary>   
    /// Gets or sets the URL.   
    /// </summary>   
    /// <value>The URL.</value>   
    public string Url { get; set; }   

In the MainViewModel we will create the resource dictionary where the Company is the key and the value will be an int and we will have a SelectedCompany property to get the company selected in the listbox.

The MainViewModel will be defined by:

C#

public class MainViewModel : ViewModelBase   
{   
   private Company _selectedCompany;   
  
   /// <summary>   
   /// Initializes a new instance of the MainViewModel class.   
   /// </summary>   
   public MainViewModel()   
   {   
      Companies = new Dictionary<Company, int>   
      {   
         {   
            new Company   
            {   
               Name = "Microsoft", Url="www.microsoft.com"   
            }, 1   
         },   
         {   
            new Company   
            {   
               Name = "Google", Url="www.google.com"   
            }, 2   
         },   
         {   
            new Company   
            {   
               Name = "Apple", Url="www.apple.com"   
            }, 3   
         }   
      };   
   }   
  
   /// <summary>   
   /// Gets or sets the selected company.   
   /// </summary>   
   /// <value>The selected company.</value>   
   public Company SelectedCompany   
   {   
      get { return _selectedCompany; }   
      set { Set(() => SelectedCompany, ref _selectedCompany, value); }   
   }   
  
   /// <summary>   
   /// Gets or sets the companies.   
   /// </summary>   
   /// <value>The companies.</value>   
   public Dictionary<Company, int> Companies { get; set; }   
}  

The MainWindow will defined as in the following:


XAML

 

<mui:ModernWindow x:Class="BindingResourceDictionarySample.MainWindow"   
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
                  xmlns:mui="http://firstfloorsoftware.com/ModernUI"   
                  Title="Sample"   
                  Width="525"   
                  Height="350"   
                  DataContext="{Binding Main,   
                                        Source={StaticResource Locator}}"   
                  Style="{StaticResource BlankWindow}">   
    <StackPanel>   
        <TextBlock Margin="20,20,0,0" Text="How to binding a Dictionary to a Listbox" />   
        <ListBox Width="250"   
                 Margin="20,20,0,0"   
                 HorizontalAlignment="Left"   
                 ItemsSource="{Binding Companies}"   
                 SelectedValue="{Binding ItemIndex}"   
                 SelectedValuePath="Key"   
                 SelectionMode="Single">   
            <ListBox.ItemTemplate>   
                <DataTemplate>   
                    <Border Width="245"   
                            BorderBrush="Orange"   
                            BorderThickness="2">   
                        <StackPanel Orientation="Horizontal">   
                            <TextBlock Margin="20,0,0,0" Text="{Binding Path=Value}" />   
                            <TextBlock Margin="20,0,0,0" Text="{Binding Path=Key.Name}" />   
                        </StackPanel>   
                    </Border>   
                </DataTemplate>   
            </ListBox.ItemTemplate>   
        </ListBox>   
    </StackPanel>   
</mui:ModernWindow>

To get the selected Company the SelectedValue property from the Listbox will be used that will use the SelectedValuePath to understand which value to return. To get the value instead of the Company we should change the Key to Value.

Note:   

  1. To have a nice look, we will use the ModernWindow from the ModernUI (for WPF). For more see the ModerUI in Modern UI Samples.
     
  2. The sample is similar to any XAML app, where we show the UI for WPF.

Running the sample
 

binding a dictonary


Source code files:

 

  • ViewModelLocator class contains static references to all the view model in the application and provide an entry point for the bindings.
     
  • MainViewModel class for binding to MainView.xaml
     
  • MainWindow represents the view.
     
  • Company defines the model.
posted Nov 2, 2015 by Jdk

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

If you want to control the visibility of a control like textblock/textbox, etc. based on the Checked or Unchecked Property of RadioButton/Checkbox , then you can use the inbuilt ‘BooleanToVisibilityConverter’ to achieve this easily. This will prevent you to write longer codes to control the visibility from CodeBehind pages. This is useful, for example, when you want to hide a certain control when a checkbox is checked and hide that control when the checkbox is unchecked.

Steps:

  1. First of all define the following code inside the <Application.Resources> </Application.Resources>tag of the App.XAML page.
    1. <local:BooleanToVisibilityConverter x:Key="MyConverter1"/>  
    code

    It is necessary to provide a key to this converter. I have given it a key of MyConverter1 . We will access this converter by using this Key from this point onwards.
     
  2. Now suppose, I have a Checkbox Control as in the following snippet whose Name isMyCheckBoxControl
    <CheckBox x:Name="MyCheckBoxControl" Content="My Check Box”/>
     .
     
  3. Similarly I have a TextBox which I want to make visible only when the CheckBox above is checked, i.e whenever IsChecked property of CheckBox is set to ‘True’. We will bind the TextBox control to the CheckBox as in the following code snippet:
    1. <TextBox x:Name="MyTextBox" Visibility="{Binding ElementName=MyCheckBox,Path=IsChecked,Converter={StaticResource MyConverter1}}" />  
    TextBox

    Here, the Visibility Property of the TextBox is binded to an ‘ElementName=MyCheckBox’ which is our Checkbox name. The ‘Path=IsChecked’ is the property which we want to be true in order to hide the TextBox and the ‘Converter={StaticResource MyConverter1}’ is the Converter that we implement to hide our TextBox.

    This gets our job done without even having to visit the CodeBehind pages.

How the Converter Works and why it is necessary?

We know, a ‘Visibility’ property only takes its value as either Visiblity.Visible or Visibility.Collapsed.
And we also know that a ‘checkbox’(or a RadioButton)’s IsChecked Property only takes its value as either ‘true’ or ‘false’.

Since a visibility property cannot take ‘true’ or ‘false’ value, so in order to assign the Visibility property’s value as Visibility.Visible or Visibility.Collapsed based on either ‘true’ or ‘false’ property of the CheckBox, we need a Converter. This Converter as its name implies converts the ‘true’ value to ‘Visibility.Visible’ and ‘false’ value to ‘Visibility.Collapsed’ and hence allows the binding to happen easily

READ MORE

We've worked a lot on windows forms applications in C#.NET.

Page load event automatically added into the form.cs file when you double click anywhere on your form in windows form application. But this is not the case in UWP Applications. UWP stands for Universal Windows platform. XAML apps does't provide you the event handler for the page when you double clicks anywhere on your page in XAML apps.

So in order to add a page load event in XAML Apps. Make a UWP Project from Visual Studio. To make a project , open visual studio and select new project as given below,

  • Select "Universal" from left side.
     
  • Choose "Blank App ( Universal Windows )". and press enter.

Open MainPage.xaml from Solution explorer. Main page with visual design will be displayed.

type an event in opening tag of "Page" named " Loaded " just like below screenshot. An event handler for the page loading will be added to .cs file behind the UI page.

Take your cursor on the name of event which is "Page_Loaded" here and press F12 , you'll be redirected to the event handler in code page.

See the screen shot of event below.

READ MORE

Data Binding with Controls

The last data binding type we will see is how to provide a data exchange between a ListBox and other controls using data binding in WPF.

We will create an application that looks as in Figure 12. In Figure 12, I have a ListBox with a list of colors, a TextBox and a Canvas. When we pick a color from the ListBox, the text of TextBox and color of Canvas changes dynamically to the color selected in the ListBox and this is possible to do all inXAML without writing a single line of code in the code behind file.

looks like Figure
                                                Figure 12.

The XAML code of the page looks as in following.

​       <StackPanel Orientation="Vertical">  
    <TextBlock Margin="10,10,10,10" FontWeight="Bold">  
        Pick a color from below list  
    </TextBlock>  
    <ListBox Name="mcListBox" Height="100" Width="100"  
             Margin="10,10,0,0" HorizontalAlignment="Left" >  
        <ListBoxItem>Orange</ListBoxItem>  
        <ListBoxItem>Green</ListBoxItem>  
        <ListBoxItem>Blue</ListBoxItem>  
        <ListBoxItem>Gray</ListBoxItem>  
        <ListBoxItem>LightGray</ListBoxItem>  
        <ListBoxItem>Red</ListBoxItem>  
    </ListBox>   
   <TextBox Height="23" Name="textBox1" Width="120" Margin="10,10,0,0" HorizontalAlignment="Left"  >  
        <TextBox.Text>  
            <Binding ElementName="mcListBox" Path="SelectedItem.Content"/>  
        </TextBox.Text>  
    </TextBox>  
    <Canvas Margin="10,10,0,0" Height="200" Width="200" HorizontalAlignment="Left" >  
        <Canvas.Background>  
            <Binding ElementName="mcListBox" Path="SelectedItem.Content"/>  
        </Canvas.Background>  
    </Canvas>  
</StackPanel>        

If you look at the TextBox XAML code, you will see the Binding within the TextBox.Text property that sets the binding from TextBox to another control and another control ID is ElementName and another control's property is Path. So in the following code, we are setting the SelectedItem.Content property ofListBox to the TextBox.Text property. 

 <TextBox.Text>  

   <Binding ElementName="mcListBox" Path="SelectedItem.Content"/>  
</TextBox.Text>  

Now the same applies to the Canvas.Background property, where we set it to theSelectedItem.Content of the ListBox. Now, every time you select an item in the ListBox, theTextBox.Text and Canvas.Background properties are set to that selected item in the ListBox.


<Canvas.Background>  
   <Binding ElementName="mcListBox" Path="SelectedItem.Content"/>  
</Canvas.Background> 

Summary

In this article, I explained how to create and use a ListBox control available in WPF and WP8. We saw how to add items to a ListBox, change item properties and add images add check boxes. In the end of this article, we saw how data binding works in ListBox and how to bind a ListBox with data coming from objects, databases and other controls. 

READ MORE

Now we add a ListBox control and set its ItemsSource property as the first DataTable of the DataSetand set ItemTemplate to the resource defined above. 

<ListBox Margin="17,8,15,26" Name="listBox1" ItemsSource="{Binding Tables[0]}"  ItemTemplate="{StaticResource listBoxTemplate}" />  

Now in our code behind, we define the following variables. 

public SqlConnection connection;  

public SqlCommand command;  

string sql = "SELECT ContactName, Address, City, Country FROM Customers"

string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True"

Now on the Windows_Loaded method, we call the BindData method and in the BindData method, we create a connection, data adapter and fill in the DataSet using the SqlDataAdapter.Fill() method.

private void Window_Loaded(object sender, RoutedEventArgs e)  
{  
    BindData();             
}  
  
private void BindData()  
{  
    DataSet dtSet = new DataSet();  
    using (connection = new SqlConnection(connectionString))  
    {  
        command = new SqlCommand(sql, connection);                 
        SqlDataAdapter adapter = new SqlDataAdapter();             
        connection.Open();  
        adapter.SelectCommand = command;  
        adapter.Fill(dtSet, "Customers");  
        listBox1.DataContext = dtSet;  
    }  
}  

Data Binding with XML 

Now let's look at how to bind XML data to a ListBox control. The XmlDataProvider is used to bind XMLdata in WPF

Here is an XmlDataProvider defined in XAML that contains books data. The XML data is defined within the x:Data tag. 

       

<XmlDataProvider x:Key="BooksData" XPath="Inventory/Books">  
    <x:XData>  
        <Inventory xmlns="">  
            <Books>  
                <Book Category="Programming" >  
                    <Title>A Programmer's Guide to ADO.NET</Title>  
                    <Summary>Learn how to write database applications using ADO.NET and C#.  
                    </Summary>  
                    <Author>Mahesh Chand</Author>  
                    <Publisher>APress</Publisher>  
                </Book>  
                <Book Category="Programming" >  
                    <Title>Graphics Programming with GDI+</Title>  
                    <Summary>Learn how to write graphics applications using GDI+ and C#.  
                    </Summary>  
                    <Author>Mahesh Chand</Author>  
                    <Publisher>Addison Wesley</Publisher>  
                </Book>  
                <Book Category="Programming" >  
                    <Title>Visual C#</Title>  
                    <Summary>Learn how to write C# applications.  
                    </Summary>  
                    <Author>Mike Gold</Author>  
                    <Publisher>APress</Publisher>  
                </Book>  
                <Book Category="Programming" >  
                    <Title>Introducing Microsoft .NET</Title>  
                    <Summary>Programming .NET  
                    </Summary>  
                    <Author>Mathew Cochran</Author>  
                    <Publisher>APress</Publisher>  
                </Book>  
                <Book Category="Database" >  
                    <Title>DBA Express</Title>  
                    <Summary>DBA's Handbook  
                    </Summary>  
                    <Author>Mahesh Chand</Author>  
                    <Publisher>Microsoft</Publisher>  
                </Book>  
            </Books>  
        </Inventory>  
    </x:XData>  
</XmlDataProvider>  

To bind an XmlDataProvider, we set the Source property inside the ItemsSource of a ListBox to thex:Key of XmlDataProvider and XPath is used to filter the data. In the ListBox.ItemTempate, we use the Binding property. 

<ListBox Width="400" Height="300" Background="LightGray">  
    <ListBox.ItemsSource>  
        <Binding Source="{StaticResource BooksData}"  
       XPath="*[@Category='Programming'] "/>  
    </ListBox.ItemsSource>  
  
    <ListBox.ItemTemplate>  
        <DataTemplate>  
            <StackPanel Orientation="Horizontal">  
                <TextBlock Text="Title: " FontWeight="Bold"/>  
                <TextBlock Foreground="Green"  >  
                    <TextBlock.Text>   
                        <Binding XPath="Title"/>  
                    </TextBlock.Text>                        
                </TextBlock>                       
           </StackPanel>  
        </DataTemplate>  
    </ListBox.ItemTemplate>  
</ListBox>  

The output of the preceding code looks as in Figure 11.

code behind file

 

READ MORE

The following XAML code generates two ListBox control and two Button controls.

<ListBox Margin="11,13,355,11" Name="LeftListBox" />  
<ListBox Margin="0,13,21,11" Name="RightListBox" HorizontalAlignment="Right" Width="216" />  
<Button Name="AddButton" Height="23" Margin="248,78,261,0" VerticalAlignment="Top"  
        Click="AddButton_Click">Add >></Button>  
<Button Name="RemoveButton" Margin="248,121,261,117"   
        Click="RemoveButton_Click"><< Remove</Button>  

On the Window loaded event, we create and load data items to the ListBox by setting the ItemsSourceproperty to an ArrayList

private void Window_Loaded(object sender, RoutedEventArgs e)  
{  
    // Get data from somewhere and fill in my local ArrayList  
    myDataList = LoadListBoxData();  
    // Bind ArrayList with the ListBox  
    LeftListBox.ItemsSource = myDataList;              
}  
  
/// <summary>  
/// Generate data. This method can bring data from a database or XML file  
/// or from a Web service or generate data dynamically  
/// </summary>  
/// <returns></returns>  
private ArrayList LoadListBoxData()  
{  
    ArrayList itemsList = new ArrayList();  
    itemsList.Add("Coffie");  
    itemsList.Add("Tea");  
    itemsList.Add("Orange Juice");  
    itemsList.Add("Milk");  
    itemsList.Add("Mango Shake");  
    itemsList.Add("Iced Tea");  
    itemsList.Add("Soda");  
    itemsList.Add("Water");  
    return itemsList;  
}  

On the Add button click event handler, we get the value and index of the selected item in the left sideListBox and add that to the right side ListBox and remove that item from the ArrayList that is our data source. The ApplyBinding method simply removes the current binding of the ListBox and rebinds with the updated ArrayList.

private void AddButton_Click(object sender, RoutedEventArgs e)  
{  
    // Find the right item and it's value and index  
    currentItemText = LeftListBox.SelectedValue.ToString();  
    currentItemIndex = LeftListBox.SelectedIndex;  
      
    RightListBox.Items.Add(currentItemText);  
    if (myDataList != null)  
    {  
        myDataList.RemoveAt(currentItemIndex);  
    }  
  
    // Refresh data binding  
    ApplyDataBinding();  
}
/// <summary>  
/// Refreshes data binding  
/// </summary>  
private void ApplyDataBinding()  
{  
    LeftListBox.ItemsSource = null;  
    // Bind ArrayList with the ListBox  
    LeftListBox.ItemsSource = myDataList;  
}  

Similarly, on the Remove button click event handler, we get the selected item text and index from the right side ListBox and add that to the ArrayList and remove from the right side ListBox.

private void RemoveButton_Click(object sender, RoutedEventArgs e)  
{  
    // Find the right item and it's value and index  
    currentItemText = RightListBox.SelectedValue.ToString();  
    currentItemIndex = RightListBox.SelectedIndex;  
    // Add RightListBox item to the ArrayList  
    myDataList.Add(currentItemText);  
  
  RightListBox.Items.RemoveAt(RightListBox.Items.IndexOf(RightListBox.SelectedItem));  
  
    // Refresh data binding  
    ApplyDataBinding();  
}  

Data Binding with a Database

We use the Northwind.mdf database that is provided with SQL Server. In our application, we will read data from the Customers table. The Customers table columns looks as in Figure 9. 

Data Binding
                                          Figure 9 

We will read ContactName, Address, City and Country columns in a WPF ListBox control. The finalListBox looks as in Figure 10. 

ContactName
                                                            Figure 10

Now let's look at our XAML file. We create a resources DataTemplate type called listBoxTemplate. A data template is used to represent data in a formatted way. The data template has two dock panels where the first panel shows the name and the second panel shows address, city and country columns using TextBlock controls. 

<Window.Resources>  
    <DataTemplate x:Key="listBoxTemplate">  
        <StackPanel Margin="3">  
            <DockPanel >  
                <TextBlock FontWeight="Bold" Text="Name:"  
                  DockPanel.Dock="Left"  
                  Margin="5,0,10,0"/>  
                <TextBlock Text="  " />  
                <TextBlock Text="{Binding ContactName}" Foreground="Green" FontWeight="Bold" />  
            </DockPanel>  
            <DockPanel >  
                <TextBlock FontWeight="Bold" Text="Address:" Foreground ="DarkOrange"   
                  DockPanel.Dock="Left"  
                  Margin="5,0,5,0"/>  
                <TextBlock Text="{Binding Address}" />  
                 <TextBlock Text=", " />  
                <TextBlock Text="{Binding City}" />  
                 <TextBlock Text=", " />  
                <TextBlock Text="{Binding Country}" />  
            </DockPanel>  
        </StackPanel>  
    </DataTemplate>  
</Window.Resources>    

 

READ MORE

   PART 2: Continuous 

 <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 as in Figure 6.

ListBox with CheckBoxes
                                 Figure 6. ListBox with CheckBoxes

Data Binding 

Before I discuss data binding in general, I must confess, Microsoft experts have made a big mess related to data-binding in .NET 3.0 and 3.5. Instead of making things simpler, they have made them complicated. Maybe they have some bigger plans for the future but so far I have seen binding using dependency objects and properties, LINQ and DLINQ and WCF and ASP.NET Web Services and it all looks like a big mess. It's not even close to the ADO.NET model we had in .NET 1.0 and 2.0. I hope they clean up this mess in the near future.

When it comes to data binding, we need to first understand the data. Here is a list of ways a data can be consumed from:

  • Objects
  • A relational database such as SQL Server
  • A XML file
  • Other controls

Data Binding with Objects

The ItemsSource property of a ListBox binds a collection of IEnuemerable items such as an ArrayList to the ListBox control. 

// Bind ArrayList with the ListBox  
LeftListBox.ItemsSource = LoadListBoxData();  

private ArrayList LoadListBoxData()  
{  
    ArrayList itemsList = new ArrayList();  
    itemsList.Add("Coffie");  
    itemsList.Add("Tea");  
    itemsList.Add("Orange Juice");  
    itemsList.Add("Milk");  
    itemsList.Add("Mango Shake");  
    itemsList.Add("Iced Tea");  
    itemsList.Add("Soda");  
    itemsList.Add("Water");  
    return itemsList;  
}  

Sample: Transferring data from one ListBox to Another 


We've seen many requirements where a page has two ListBox controls and the left ListBox displays a list of items and using a button we can add items from the left ListBox and add them to the right side ListBoxand using the remove button we can remove items from the right side ListBox and add them back to the left side ListBox

This sample shows how to move items from one ListBox to another. The final page looks as in Figure 7. The Add button adds the selected item to the right side ListBox and removes from the left side ListBox. The Remove button removes the selected item from the right side ListBox and adds back to the left sideListBox.

ListBox
                                                                           Figure 7

add remove
                                                                           Figure 8

 

PART 4: will update soon

READ MORE

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 the background and foreground colors of aListBoxItem.

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

The FontFamilyFontSize and FontWeight are used to set a font of a ListBoxItem. The following code snippet sets the font to verdana, the size to 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 as in Figure 4. 

Formatted ListBox
                                       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 beside 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 the 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 as in Figure 5. 


ListBoxItems with Image
                           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 the 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 the following CheckBoxes to the items. As you may see, I have set the name of the CheckBoxes using the Name property. If you need to access these CheckBoxes, you may access them in the code using their Name property. 

Part 3 Will Update Soon

READ MORE
...