Freigeben über


ItemsControl Content Model Overview

This content model overview describes the supported content for an ItemsControl. The ListBox control is a type of ItemsControl.

This topic contains the following sections.

  • ItemsControl Content Properties
  • Using the Items Property
  • Using the ItemsSource Property
  • Types That Share This Content Model
  • Types That Can Contain ItemsControl Objects
  • Related Topics

ItemsControl Content Properties

An ItemsControl has the following content properties.

In the following illustration, ListBoxItem1, ListBoxItem2, and ListBoxItem3 are examples of Items in a ListBox control.

ItemsControl example

Using the Items Property

The Items property can contain items like strings, objects, or other elements. The following example shows how to use the Items property to add content to a Menu control.

<Menu>
  <Menu.Items>
    <TextBlock>My Text</TextBlock>
    <Button>My Button</Button>
  </Menu.Items>
</Menu>
Menu myMenu = new Menu();

TextBlock myTextBlock = new TextBlock();
myTextBlock.Text = "My Text";
myMenu.Items.Add(myTextBlock);

Button myButton = new Button();
myButton.Content = "My Button";
myMenu.Items.Add(myButton);

Using the ItemsSource Property

You can set the ItemsSource property to a collection of items.

The following example shows an ObservableCollection that you can use as an ItemsSource.

public class myData: ObservableCollection<string>
{
  public myData()
  {
    Add("TreeViewItem_1");
    Add("TreeViewItem_2");
    Add("TreeViewItem_3");
  }

The following example uses XAML to specify a ResourceKey for the collection that is used to set the ItemsSource of the ListBox.

<ObjectDataProvider x:Key="myTreeViewData" ObjectType="{x:Type src:myData}"/>
<ListBox Background="Aqua" 
         ItemsSource ="{Binding Source={StaticResource myTreeViewData}}"/>

The following example creates the same ListBox by using code.

ObjectDataProvider myListBoxData = new ObjectDataProvider();
myListBoxData.ObjectType = Type.GetType("SDKSample.myData"); 
ListBox myListBox = new ListBox();
Binding bind2obj = new Binding();
bind2obj.Source = myListBoxData;
myListBox.Background = Brushes.Beige;
myListBox.SetBinding(ListBox.ItemsSourceProperty, bind2obj);

Types That Share This Content Model

The following classes inherit from the ItemsControl class. You can use these classes to display the content that is described in this overview.

NoteNote:

Although the MenuItem, ToolBar, and TreeViewItem classes also inherit from ItemsControl, these controls are discussed separately. For more information, see HeaderedItemsControl Content Model Overview.

Types That Can Contain ItemsControl Objects

You can use the ItemsControl class as content for the following types:

See Also

Reference

ItemsControl
ListBox

Concepts

HeaderedItemsControl Content Model Overview