Search This Blog

Monday, November 11, 2013

ListBox WPF Example

WPF > ControlsItemsControl > ListBox

ListBox contains a list of selectable items.
It can contain a collection of objects of any type (string, image,  panel).

1. ListBox ItemsSource example:

XAML:

<Window x:Class="LIstBoxExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:LIstBoxExample"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <src:Cars x:Key="carsData"/>
        </Grid.Resources>
        <ListBox ItemsSource="{StaticResource carsData}"  DisplayMemberPath="Model" Margin="114,0,207,0"/>
    </Grid>
</Window>

 
Code:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LIstBoxExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>

    public class Car
    {
        public String Model { get; set; }
        public Car(String model)
        {
            this.Model = model;  
        }
    }

    public class Cars : ObservableCollection<Car>
    {
        public Cars()
        {
            Add(new Car("Audi"));
            Add(new Car("Mercedes"));
        }
    }
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}


2. ListBox Items example:

XAML:


<ListBox x:Name="lstItems" HorizontalAlignment="Left" Height="300" VerticalAlignment="Top" Width="171" Margin="324,10,0,0"/>

Code:

    // Add string to ListBox
            lstItems.Items.Add("String Item");

            // Add date to ListBox
            DateTime dateTime1 = DateTime.Now;
            lstItems.Items.Add(dateTime1);

            // Add a Rectangle to the ListBox.
            Rectangle rect1 = new Rectangle();
            rect1.Width = 20;
            rect1.Height = 20;
            rect1.Fill = Brushes.Red ;
            lstItems.Items.Add(rect1);