Items​Control Class

Definition

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

[System.Windows.Localizability(System.Windows.LocalizationCategory.None, Readability=System.Windows.Readability.Unreadable)]
[System.Windows.Markup.ContentProperty("Items")]
[System.Windows.StyleTypedProperty(Property="ItemContainerStyle", StyleTargetType=typeof(System.Windows.FrameworkElement))]
public class ItemsControl : System.Windows.Controls.Control, System.Windows.Controls.Primitives.IContainItemStorage, System.Windows.Markup.IAddChild
Inheritance
Derived
Attributes
Implements

Inherited Members

System.Object

System.Windows.Controls.Control

System.Windows.DependencyObject

System.Windows.FrameworkElement

System.Windows.Media.Visual

System.Windows.Threading.DispatcherObject

System.Windows.UIElement

Examples

The following examples demonstrate binding data to an ItemsControl. The first example creates a class called MyData that is a simple string collection.

public class MyData : ObservableCollection<string>
{
    public MyData()
    {
        Add("Item 1");
        Add("Item 2");
        Add("Item 3");
    }
}
Public Class MyData
    Inherits ObservableCollection(Of String)

    Public Sub New()  '

        Add("Item 1")
        Add("Item 2")
        Add("Item 3")

    End Sub 'New
End Class 'MyData

The following example binds the ItemsSource object of an ItemsControl to MyData.

<!--Create an instance of MyData as a resource.-->
<src:MyData x:Key="dataList"/>
<ListBox ItemsSource="{Binding Source={StaticResource dataList}}"/>
ListBox listBox1 = new ListBox();
MyData listData = new MyData();
Binding binding1 = new Binding();

binding1.Source = listData;
listBox1.SetBinding(ListBox.ItemsSourceProperty, binding1);
Dim listBox1 As New ListBox()
Dim listData As New MyData()
Dim binding1 As New Binding()

binding1.Source = listData
listBox1.SetBinding(ListBox.ItemsSourceProperty, binding1)

The following illustration shows the ListBox control created in the previous example.

ListBox

The following example demonstrates how to populate an ItemsControl by using the Items property. The example adds the following different types of items to the ListBox:

<!--Create a ListBox that contains a string, a Rectangle,
     a Panel, and a DateTime object. These items can be accessed
     via the Items property.-->
<ListBox xmlns:sys="clr-namespace:System;assembly=mscorlib"
         Name="simpleListBox">

  <!-- The <ListBox.Items> element is implicitly used.-->
  This is a string in a ListBox

  <sys:DateTime>2004/3/4 13:6:55</sys:DateTime>

  <Rectangle Height="40" Width="40"  Fill="Blue"/>

  <StackPanel Name="itemToSelect">
    <Ellipse Height="40" Fill="Blue"/>
    <TextBlock>Text below an Ellipse</TextBlock>
  </StackPanel>

  <TextBlock>String in a TextBlock</TextBlock>
</ListBox>
// Add a String to the ListBox.
listBox1.Items.Add("This is a string in a ListBox");

// Add a DateTime object to a ListBox.
DateTime dateTime1 = new DateTime(2004, 3, 4, 13, 6, 55);

listBox1.Items.Add(dateTime1);

// Add a Rectangle to the ListBox.
Rectangle rect1 = new Rectangle();
rect1.Width = 40;
rect1.Height = 40;
rect1.Fill = Brushes.Blue;
listBox1.Items.Add(rect1);

// Add a panel that contains multpile objects to the ListBox.
Ellipse ellipse1 = new Ellipse();
TextBlock textBlock1 = new TextBlock();

ellipse1.Width = 40;
ellipse1.Height = 40;
ellipse1.Fill = Brushes.Blue;

textBlock1.TextAlignment = TextAlignment.Center;
textBlock1.Text = "Text below an Ellipse";

stackPanel1.Children.Add(ellipse1);
stackPanel1.Children.Add(textBlock1);

listBox1.Items.Add(stackPanel1);
' Create a Button with a string as its content.
listBox1.Items.Add("This is a string in a ListBox")

' Create a Button with a DateTime object as its content.
Dim dateTime1 As New DateTime(2004, 3, 4, 13, 6, 55)

listBox1.Items.Add(dateTime1)

' Create a Button with a single UIElement as its content.
Dim rect1 As New Rectangle()
rect1.Width = 40
rect1.Height = 40
rect1.Fill = Brushes.Blue
listBox1.Items.Add(rect1)

' Create a Button with a panel that contains multiple objects 
' as its content.
Dim ellipse1 As New Ellipse()
Dim textBlock1 As New TextBlock()

ellipse1.Width = 40
ellipse1.Height = 40
ellipse1.Fill = Brushes.Blue

textBlock1.TextAlignment = TextAlignment.Center
textBlock1.Text = "Text below an Ellipse"

stackPanel1.Children.Add(ellipse1)
stackPanel1.Children.Add(textBlock1)

listBox1.Items.Add(stackPanel1)

The following illustration shows the ListBox created in the previous example.

ListBox with four types of content

The following example illustrates how to use the different styling and templating-related properties that are provided by the ItemsControl. The ItemsControl in this example is bound to a collection of Task objects. For demonstration purposes, the styles and templates in this example are all declared inline.

<ItemsControl Margin="10"
              ItemsSource="{Binding Source={StaticResource myTodoList}}">
  <!--The ItemsControl has no default visual appearance.
      Use the Template property to specify a ControlTemplate to define
      the appearance of an ItemsControl. The ItemsPresenter uses the specified
      ItemsPanelTemplate (see 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.-->
  <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>
      <WrapPanel />
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
  <!--Use the ItemTemplate to set a DataTemplate to define
      the visualization 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>
      <DataTemplate.Resources>
        <Style TargetType="TextBlock">
          <Setter Property="FontSize" Value="18"/>
          <Setter Property="HorizontalAlignment" Value="Center"/>
        </Style>
      </DataTemplate.Resources>
      <Grid>
        <Ellipse Fill="Silver"/>
        <StackPanel>
          <TextBlock Margin="3,3,3,0"
                     Text="{Binding Path=Priority}"/>
          <TextBlock Margin="3,0,3,7"
                     Text="{Binding Path=TaskName}"/>
        </StackPanel>
      </Grid>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
  <!--Use the ItemContainerStyle property to specify the appearance
      of the element that contains the data. This ItemContainerStyle
      gives each item container a margin and a width. There is also
      a trigger that sets a tooltip that shows the description of
      the data object when the mouse hovers over the item container.-->
  <ItemsControl.ItemContainerStyle>
    <Style>
      <Setter Property="Control.Width" Value="100"/>
      <Setter Property="Control.Margin" Value="5"/>
      <Style.Triggers>
        <Trigger Property="Control.IsMouseOver" Value="True">
          <Setter Property="Control.ToolTip"
                  Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                          Path=Content.Description}"/>
        </Trigger>
      </Style.Triggers>
    </Style>
  </ItemsControl.ItemContainerStyle>
</ItemsControl>

The following illustration is a screenshot of the example when it is rendered.

ItemsControl example screenshot

Two other style-related properties of the ItemsControl that are not shown here are GroupStyle and GroupStyleSelector.

Remarks

An ItemsControl is a type of Control that can contain multiple items, such as strings, objects, or other elements. The following illustration shows a ListBox control that contains the following different types of items:

ListBox with four types of content
ListBox that contains multiple types of objects

Use either the Items or the ItemsSource property to specify the collection to use to generate the content of your ItemsControl. You can set the ItemsSource property to any type that implements IEnumerable. ItemsSource is typically used to display a data collection or to bind an ItemsControl to a collection object.

If you do not want to use an object that implements IEnumerable to populate the ItemsControl, you can add items by using the Items property. The items in an ItemsControl can have different types. For example, a ListBox can contain one item that is a string and another item that is an Image.

When the ItemsSource property is set, the Items collection is set to read-only and fixed-size. This means that you cannot add items to the collection directly. When ItemsSource is in use, setting the property to null removes the collection and restores usage to Items, which will be an empty ItemCollection.

Each ItemsControl type has a corresponding item container type. The corresponding item container for each ItemsControl appends Item to its name. For example, for ListBox, the item containers are ListBoxItem controls; for ComboBox, they are ComboBoxItem controls. You can explicitly create a container type for each item in the ItemsControl, but it is not necessary. When you do not explicitly create the container type, one is generated that contains a data item in the item collection. For example, if you bind a collection of string objects to the ItemsSource property of a ListBox, you do not explicitly create ListBoxItem objects, but the ListBox will generate one for each string. You can access a generated item container by using the ItemContainerGenerator property.

Note

Certain features of UI Automation do not work correctly when an ItemsControl contains duplicate objects. If an object appears multiple times, only the first instance appears in the automation tree. (Two objects x and y are considered to be duplicates if Object.Equals(x, y) returns true.)

While an object x is in use by an ItemsControl the value returned by x.GetHashCode() must not change. Changes to this value are unsupported, and lead to unpredictable behavior.

Dependency properties for this control might be set by the control’s default style. If a property is set by a default style, the property might change from its default value when the control appears in the application. The default style is determined by which desktop theme is used when the application is running. For more information, see Default WPF Themes.

Constructors

Items​Control()

Initializes a new instance of the ItemsControl class.

Fields

Alternation​Count​Property

Identifies the AlternationCount dependency property.

Alternation​Index​Property

Identifies the System.Windows.Controls.ItemsControl.AlternationIndex dependency property.

Display​Member​Path​Property

Identifies the DisplayMemberPath dependency property.

Group​Style​Selector​Property

Identifies the GroupStyleSelector dependency property.

Has​Items​Property

Identifies the HasItems dependency property.

Is​Grouping​Property

Identifies the IsGrouping dependency property.

Is​Text​Search​Case​Sensitive​Property

Identifies the IsTextSearchCaseSensitive dependency property.

Is​Text​Search​Enabled​Property

Identifies the IsTextSearchEnabled dependency property.

Item​Binding​Group​Property

Identifies the ItemBindingGroup dependency property.

Item​Container​Style​Property

Identifies the ItemContainerStyle dependency property.

Item​Container​Style​Selector​Property

Identifies the ItemContainerStyleSelector dependency property.

Items​Panel​Property

Identifies the ItemsPanel dependency property.

Items​Source​Property

Identifies the ItemsSource dependency property.

Item​String​Format​Property

Identifies the ItemStringFormat dependency property.

Item​Template​Property

Identifies the ItemTemplate dependency property.

Item​Template​Selector​Property

Identifies the ItemTemplateSelector dependency property.

Properties

Alternation​Count

Gets or sets the number of alternating item containers in the ItemsControl, which enables alternating containers to have a unique appearance.

Display​Member​Path

Gets or sets a path to a value on the source object to serve as the visual representation of the object.

Group​Style

Gets a collection of GroupStyle objects that define the appearance of each level of groups.

Group​Style​Selector

Gets or sets a method that enables you to provide custom selection logic for a GroupStyle to apply to each group in a collection.

Has​Items

Gets a value that indicates whether the ItemsControl contains items.

Is​Grouping

Gets a value that indicates whether the control is using grouping.

Is​Text​Search​Case​Sensitive

Gets or sets a value that indicates whether case is a condition when searching for items.

Is​Text​Search​Enabled

Gets or sets a value that indicates whether TextSearch is enabled on the ItemsControl instance.

Item​Binding​Group

Gets or sets the BindingGroup that is copied to each item in the ItemsControl.

Item​Container​Generator

Gets the ItemContainerGenerator that is associated with the control.

Item​Container​Style

Gets or sets the Style that is applied to the container element generated for each item.

Item​Container​Style​Selector

Gets or sets custom style-selection logic for a style that can be applied to each generated container element.

Items

Gets the collection used to generate the content of the ItemsControl.

Items​Panel

Gets or sets the template that defines the panel that controls the layout of items.

Items​Source

Gets or sets a collection used to generate the content of the ItemsControl.

Item​String​Format

Gets or sets a composite string that specifies how to format the items in the ItemsControl if they are displayed as strings.

Item​Template

Gets or sets the DataTemplate used to display each item.

Item​Template​Selector

Gets or sets the custom logic for choosing a template used to display each item.

Logical​Children

Gets an enumerator for the logical child objects of the ItemsControl object.

Methods

Add​Child(​Object)

Adds the specified object as the child of the ItemsControl object.

Add​Text(​String)

Adds the specified text string to the ItemsControl object.

Begin​Init()

Indicates that the initialization of the ItemsControl object is about to start.

Clear​Container​For​Item​Override(​Dependency​Object, ​Object)

When overridden in a derived class, undoes the effects of the PrepareContainerForItemOverride(DependencyObject, Object) method.

Container​From​Element(​Items​Control, ​Dependency​Object)

Returns the container that belongs to the specified ItemsControl that owns the given container element.

Container​From​Element(​Dependency​Object)

Returns the container that belongs to the current ItemsControl that owns the given element.

End​Init()

Indicates that the initialization of the ItemsControl object is complete.

Get​Alternation​Index(​Dependency​Object)

Gets the System.Windows.Controls.ItemsControl.AlternationIndex for the specified object.

Get​Container​For​Item​Override()

Creates or identifies the element that is used to display the given item.

Get​Items​Owner(​Dependency​Object)

Returns the ItemsControl that the specified element hosts items for.

Is​Item​Its​Own​Container(​Object)

Determines if the specified item is (or is eligible to be) its own container.

Is​Item​Its​Own​Container​Override(​Object)

Determines if the specified item is (or is eligible to be) its own container.

Items​Control​From​Item​Container(​Dependency​Object)

Returns the ItemsControl that owns the specified container element.

On​Alternation​Count​Changed(​Int32, ​Int32)

Invoked when the AlternationCount property changes.

On​Display​Member​Path​Changed(​String, ​String)

Invoked when the DisplayMemberPath property changes.

On​Group​Style​Selector​Changed(​Group​Style​Selector, ​Group​Style​Selector)

Invoked when the GroupStyleSelector property changes.

On​Item​Binding​Group​Changed(​Binding​Group, ​Binding​Group)

Invoked when the ItemBindingGroup property changes.

On​Item​Container​Style​Changed(​Style, ​Style)

Invoked when the ItemContainerStyle property changes.

On​Item​Container​Style​Selector​Changed(​Style​Selector, ​Style​Selector)

Invoked when the ItemContainerStyleSelector property changes.

On​Items​Changed(​Notify​Collection​Changed​Event​Args)

Invoked when the Items property changes.

On​Items​Panel​Changed(​Items​Panel​Template, ​Items​Panel​Template)

Invoked when the ItemsPanel property changes.

On​Items​Source​Changed(​IEnumerable, ​IEnumerable)

Called when the ItemsSource property changes.

On​Item​String​Format​Changed(​String, ​String)

Invoked when the ItemStringFormat property changes.

On​Item​Template​Changed(​Data​Template, ​Data​Template)

Invoked when the ItemTemplate property changes.

On​Item​Template​Selector​Changed(​Data​Template​Selector, ​Data​Template​Selector)

Invoked when the ItemTemplateSelector property changes.

On​Key​Down(​Key​Event​Args)

Invoked when the KeyDown event is received.

On​Text​Input(​Text​Composition​Event​Args)

Invoked when the TextInput event is received.

Prepare​Container​For​Item​Override(​Dependency​Object, ​Object)

Prepares the specified element to display the specified item.

Should​Apply​Item​Container​Style(​Dependency​Object, ​Object)

Returns a value that indicates whether to apply the style from the ItemContainerStyle or ItemContainerStyleSelector property to the container element of the specified item.

Should​Serialize​Group​Style()

Returns a value that indicates whether serialization processes should serialize the effective value of the GroupStyle property.

Should​Serialize​Items()

Returns a value that indicates whether serialization processes should serialize the effective value of the Items property.

To​String()

Provides a string representation of the ItemsControl object.

Explicit Interface Implementations

I​Contain​Item​Storage.​Clear()

Clears all property associations.

I​Contain​Item​Storage.​Clear​Item​Value(​Object, ​Dependency​Property)

Removes the association between the specified item and property.

I​Contain​Item​Storage.​Clear​Value(​Dependency​Property)

Removes the specified property from all property lists.

I​Contain​Item​Storage.​Read​Item​Value(​Object, ​Dependency​Property)

Returns the value of the specified property that is associated with the specified item.

I​Contain​Item​Storage.​Store​Item​Value(​Object, ​Dependency​Property, ​Object)

Stores the specified property and value and associates them with the specified item.

I​Add​Child.​Add​Child(​Object)

This member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code.

I​Add​Child.​Add​Text(​String)

This member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code.