Posted by: Zeeshan Amjad | September 29, 2009

Using Collection class in XAML


XAML is not WPF specific technology and it is not only used in WPF. It can also be used in other technologies, in fact Windows Workflow is already using XAML. We can also used other .Net class in in XAML.

Here is a simple XAML code to demonstrate how we can make List of string in XAML.

 

  1: <Window x:Class="xaml2.Window1"
  2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3:     xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
  4:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5:     xmlns:sys="clr-namespace:System;assembly=mscorlib"
  6:     Title="XAML" Height="300" Width="300">
  7:     <Window.Resources>
  8:         <x:Array x:Key="MyList" Type="{x:Type sys:String}">
  9:             <sys:String>Maryland</sys:String>
 10:             <sys:String>California</sys:String>
 11:             <sys:String>Virginia</sys:String>
 12:         </x:Array>
 13:     </Window.Resources>    
 14: 
 15: </Window>
 16: 

This XAML code is equivalent to this C# code.

  1: List<String> MyList = new List<string>();
  2: 
  3: MyList.Add("Maryland");
  4: MyList.Add("California");
  5: MyList.Add("Virginia");

Now lets use this string with list box. Here is a simple code to insert these items in List Box.

 

  1: <Window x:Class="xaml2.Window1"
  2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3:     xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
  4:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5:     xmlns:sys="clr-namespace:System;assembly=mscorlib"
  6:     Title="XAML" Height="300" Width="300">
  7:     <Window.Resources>
  8:         <x:Array x:Key="MyList" Type="{x:Type sys:String}">
  9:             <sys:String>Maryland</sys:String>
 10:             <sys:String>California</sys:String>
 11:             <sys:String>Virginia</sys:String>
 12:         </x:Array>
 13:     </Window.Resources>
 14:     
 15:     <Grid>
 16:         <ListBox Name="lst" Margin="5" ItemsSource="{StaticResource MyList}">
 17: 
 18:         </ListBox>
 19:     </Grid>
 20: </Window>
 21: 

Here is the output of this program.

XAML_01

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: