Collections are used to work with a group of items and .NET provides a good list of types to deal with collections. If you want to learn more about collections, check out the articles .NET Collections with C# and Generic Collection Classes in C# for more details.
Sometimes we need to use a collection type within XAML code. XAML allows developers to access .NET class library collection types form the scripting language.
The first step to call a collection in XAML is to import the collection namespace in XAML.
The code snippet in Listing 1 creates an array of String types, a collection of strings. To use the Array and String types, we must import the System namespace.
The code listing in Listing 1 creates an Array of String objects in XAML. As you may have noticed in Listing 2, you must import the System namespace in XAML using the xmlns.
- <Window x:Class="XamlCollectionsSample.MainWindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:sys="clr-namespace:System;assembly=mscorlib"
- Title="MainWindow" Height="402.759" Width="633.345">
-
- <Window.Resources>
- <x:Array x:Key="AuthorList" Type="{x:Type sys:String}">
- <sys:String>Mahesh Chand</sys:String>
- <sys:String>Praveen Kumar</sys:String>
- <sys:String>Raj Beniwal</sys:String>
- <sys:String>Neel Beniwal</sys:String>
- <sys:String>Sam Hobbs</sys:String>
- </x:Array>
- </Window.Resources>
-
- </Window>
Listing 1
The ItemsSource property of ListBox in XAML is used to bind the ArrayList. See Listing 2.
- <ListBox Name="lst" Margin="5" ItemsSource="{StaticResource AuthorList}" />
Listing 2