Access Collection Types in XAML

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.

 

  1. <Window x:Class="XamlCollectionsSample.MainWindow"  
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4. xmlns:sys="clr-namespace:System;assembly=mscorlib"  
  5. Title="MainWindow" Height="402.759" Width="633.345">  
  6.   
  7. <Window.Resources>  
  8. <x:Array x:Key="AuthorList" Type="{x:Type sys:String}">  
  9. <sys:String>Mahesh Chand</sys:String>  
  10. <sys:String>Praveen Kumar</sys:String>  
  11. <sys:String>Raj Beniwal</sys:String>  
  12. <sys:String>Neel Beniwal</sys:String>  
  13. <sys:String>Sam Hobbs</sys:String>  
  14. </x:Array>  
  15. </Window.Resources>  
  16.   
  17. </Window>  

 

Listing 1

The ItemsSource property of ListBox in XAML is used to bind the ArrayList. See Listing 2.

 

  1. <ListBox Name="lst" Margin="5" ItemsSource="{StaticResource AuthorList}" />  

 

Listing 2


Recommended Free Ebook
Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.