ItemsControl Class
This page is specific to:Microsoft Version:
3.03.5Silverlight 34
.NET Framework Class Library for Silverlight
ItemsControl Class

Represents a control that can be used to present a collection of items.

Namespace:  System.Windows.Controls
Assembly:  System.Windows (in System.Windows.dll)
Syntax

'Usage

Dim instance As ItemsControl

'Declaration

<ContentPropertyAttribute("Items", True)> _
Public Class ItemsControl _
    Inherits Control
<ItemsControl ...>
  oneOrMoreItems
</ItemsControl>

XAML Values

oneOrMoreItems

One or more object elements. These elements become items in the Items collection.

Remarks

In general, an ItemsControl serves two roles. It can be used to present a fixed set of items, or it can be used to display a list obtained from data binding to an object. There are several controls that inherit from ItemsControl that you can use in your application, but you can also use an ItemsControl directly. For example, if you have a collection of data that you want to display as a nonselectable list, you can use an ItemsControl to contain the data. Regardless of whether you use the ItemsControl or a child class, you can use the ItemTemplate to specify the appearance of each item.

If you want to display a fixed list, populate Items with one or more FrameworkElement child objects, and leave DisplayMemberPath as the default empty string. Do not specify ItemsSource.

If you want to display data from an object source, specify ItemsSource to be a reference to an object. Usually you do this through a Binding declaration, and the resolution mechanism for the object being used as the binding source is potentially influenced by the acting DataContext. You can set DisplayMemberPath to be the name or path of the particular property that should be displayed as repeating data by using a default display for the returned object. Or you can leave DisplayMemberPath as the default empty string, and specify a DataTemplate for ItemTemplate. This last approach gives you more control of the visual representation of each item, and it also enables you to display multiple properties of each data-bound object within each item by using a layout that you define in the template.

Examples

The following example creates a page with several ListBox controls, which inherit from ItemsControl, configured in a variety of ways.

Run this sample

<UserControl x:Class="ListBoxSnippetEx.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:src="clr-namespace:ListBoxSnippetEx"
     >

    <StackPanel x:Name="LayoutRoot" Background="White" Margin="10,10,10,10">
        <StackPanel Orientation="Horizontal" >
            <TextBlock Margin="5" Text="ListBox with unbound data:" />
        <ListBox Width="150" Margin="0,5,0,10">
            <TextBlock Text="TextBlock" />
            <TextBox Text="TextBox" />
            <Button Content="Button"  />
            <Rectangle Fill="LightBlue" Height="20" Width="100"  Margin="2,2,2,2"/>
            <Ellipse Fill="Coral" Height="20" Width="150"  Margin="2,2,2,2"/>
        </ListBox>

        <TextBlock Margin="5" Text="ListBox with bound data:" />
        <Grid>
            <Grid.Resources>
                <src:Customers x:Key="customers"/>
            </Grid.Resources>
            <ListBox ItemsSource="{StaticResource customers}" Width="250" Margin="0,5,0,10" 
               DisplayMemberPath="LastName"/>
        </Grid>
</StackPanel>
        <StackPanel Orientation="Horizontal" >
            <TextBlock Margin="5" Text="ListBox with ItemTemplate:" Width="160" />
            <Grid>
                <Grid.Resources>
                    <src:Customers x:Key="customers"/>
                </Grid.Resources>

                <ListBox ItemsSource="{StaticResource customers}" Width="350" Margin="0,5,0,10">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Padding="5,0,5,0"
                      Text="{Binding FirstName}" />
                                <TextBlock Text="{Binding LastName}" />
                                <TextBlock Text=", " />
                                <TextBlock Text="{Binding Address}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </Grid>
            <Grid>
                <Grid.Resources>
                    <Style x:Key="horizontalListBoxStyle" TargetType="ListBox">
                        <Setter Property="ItemsPanel">
                            <Setter.Value>
                                <ItemsPanelTemplate>
                                    <StackPanel Orientation="Horizontal"
                            VerticalAlignment="Center"
                            HorizontalAlignment="Center"/>
                                </ItemsPanelTemplate>
                            </Setter.Value>
                        </Setter>
                        <Setter Property="ItemTemplate">
                            <Setter.Value>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Padding="5,0,5,0"
                          Text="{Binding FirstName}" />
                                        <TextBlock Text="{Binding LastName}" />
                                    </StackPanel>
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>

                    <src:Customers x:Key="items"/>
                </Grid.Resources>
                <ListBox Height="25" Width="420" ItemsSource="{StaticResource items}" Style="{StaticResource horizontalListBoxStyle}"/>
            </Grid>
        </StackPanel>
        <TextBlock Margin="5" Text="ListBox with SelectionChanged event handler:" Width="270" HorizontalAlignment="Left" />
            <ListBox Width="150" Margin="0,5,0,5" SelectionChanged="PrintText" HorizontalAlignment="Left">
                <ListBoxItem Content="Item 1" />
                <ListBoxItem Content="Item 2" />
                <ListBoxItem Content="Item 3" />
                <ListBoxItem Content="Item 4" />
                <ListBoxItem Content="Item 5" />
            </ListBox>
            <TextBlock Name="textBlock1" />
     </StackPanel>
</UserControl>
Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Ink
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports System.Collections.ObjectModel

Partial Public Class Page
    Inherits UserControl
    Public Sub New()
        ' Required to initialize variables 
        InitializeComponent()
    End Sub

    Private Sub PrintText(ByVal sender As Object, ByVal args As SelectionChangedEventArgs)
        Dim lbi As ListBoxItem = TryCast(TryCast(sender, ListBox).SelectedItem, ListBoxItem)
        textBlock1.Text = " You selected " + lbi.Content.ToString() + "."
    End Sub

End Class


Public Class Customer
    Private _firstName As String
    Private _lastName As String
    Private _address As String

    Public Property FirstName() As String
        Get
            Return _firstName
        End Get

        Set(ByVal value As String)
            _firstName = value
        End Set
    End Property

    Public Property LastName() As String
        Get
            Return _lastName
        End Get

        Set(ByVal value As String)
            _lastName = value
        End Set
    End Property

    Public Property Address() As String
        Get
            Return _address
        End Get

        Set(ByVal value As String)
            _address = value
        End Set
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String, ByVal address As String)
        Me.FirstName = firstName
        Me.LastName = lastName
        Me.Address = address
    End Sub

End Class

Public Class Customers
    Inherits ObservableCollection(Of Customer)

    Public Sub New()
        Add(New Customer("Michael", "Anderberg", "12 North Third Street, Apartment 45"))
        Add(New Customer("Chris", "Ashton", "34 West Fifth Street, Apartment 67"))
        Add(New Customer("Cassie", "Hicks", "56 East Seventh Street, Apartment 89"))
        Add(New Customer("Guido", "Pica", "78 South Ninth Street, Apartment 10"))
    End Sub

End Class



The following example creates an ItemsControl. By default, an ItemsControl lists items but does not have any other visual characteristics, such as chrome. The example specifies a ControlTemplate to give the ItemsControl a border. It also specifies a DataTemplate to specify the appearance of each item and an ItemsPanelTemplate to lay out the items horizontally.

<Grid>
  <Grid.Resources>
    <src:Tasks x:Key="myTodoList"/>
  </Grid.Resources>  
  <ItemsControl Margin="10" Width="400" 
            ItemsSource="{Binding Source={StaticResource myTodoList}}">
    <!--Use the Template property to specify a ControlTemplate to define
    the appearance of an ItemsControl. The ItemsPresenter uses the specified
    ItemsPanelTemplate (defined below) to layout the items. If an
    ItemsPanelTemplate is not specified, the default is used. (For ItemsControl,
    the default is an ItemsPanelTemplate that specifies a StackPanel that
    arranges items vertically.)-->
    <ItemsControl.Template>
      <ControlTemplate TargetType="ItemsControl">
        <Border BorderBrush="Aqua" BorderThickness="1" CornerRadius="15">
          <ItemsPresenter/>
        </Border>
      </ControlTemplate>
    </ItemsControl.Template>
    <!--Use the ItemsPanel property to specify an ItemsPanelTemplate
    that defines the panel that is used to hold the generated items.
    In other words, use this property if you want to affect
    how the items are laid out.-->
    <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal"/>
      </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <!--Use the ItemTemplate to set a DataTemplate to define
    the appeatance of the data objects. This DataTemplate
    specifies that each data object appears with the Proriity
    and TaskName on top of a silver ellipse.-->
    <ItemsControl.ItemTemplate>
      <DataTemplate>
        <Grid Width="70" Margin="5">
          <Ellipse Fill="Silver"/>
          <StackPanel>
            <TextBlock Margin="3,3,3,0" FontSize="12" HorizontalAlignment="Center"
                   Text="{Binding Path=Priority}"/>
            <TextBlock Margin="3,0,3,7" FontSize="12" HorizontalAlignment="Center"
                   Text="{Binding Path=TaskName}"/>
          </StackPanel>
        </Grid>
      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
</Grid>
public class Task : INotifyPropertyChanged
{
    private string name;
    private int priority;


    public event PropertyChangedEventHandler PropertyChanged;

    public Task()
    {
    }

    public Task(string name, int priority)
    {
        this.name = name;
        this.priority = priority;
    }

    public override string ToString()
    {
        return name.ToString();
    }

    public string TaskName
    {
        get { return name; }
        set
        {
            name = value;
            OnPropertyChanged("TaskName");
        }
    }

    public int Priority
    {
        get { return priority; }
        set
        {
            priority = value;
            OnPropertyChanged("Priority");
        }
    }

    protected void OnPropertyChanged(string info)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(info));
        }
    }
}

public class Tasks : ObservableCollection<Task>
{
    public Tasks()
        : base()
    {
        Add(new Task("Shopping", 2));
        Add(new Task("Laundry", 2));
        Add(new Task("Email", 1));
        Add(new Task("Clean", 3));
        Add(new Task("Dinner", 1));
    }
}


The previous example produces output that resembles the following illustration.

Customized ItemsControl

Customized ItemsControl
Inheritance Hierarchy

System..::.Object
  System.Windows..::.DependencyObject
    System.Windows..::.UIElement
      System.Windows..::.FrameworkElement
        System.Windows.Controls..::.Control
          System.Windows.Controls..::.ItemsControl
            System.Windows.Controls..::.HeaderedItemsControl
            System.Windows.Controls.Primitives..::.Selector
            System.Windows.Controls..::.TabControl
            System.Windows.Controls..::.TreeView
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

See Also

Reference

Other Resources

© 2010 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View