Charles Petzold

How to Index Arrays in XAML

May 10, 2006
New York City

Suppose you need to obtain a string for the name of the current month. In C#, it's trivial. You start off with using directives for System and System.Globalization and then index the MonthNames array of DateTimeFormatInfo with the Month property of a DateTime object, remembering to convert the Month from 1-based to 0-based:

However, doing something similar in XAML isn't quite as straightforward. (For the following examples, the 's' prefix refers to an XML namespace for System and 'g' for System.Globalization.) You can easily use a Binding to display the current month number, like so:

That will display the number 5 for the month of May. You can also specify a numeric index of the MonthNames array. This XAML displays the string "May":

However, merging these two bindings just doesn't work.

It is possible to index an array in XAML, however. The trick is finding a class that indexes arrays, and it's more obvious than it may seem. ListBox, for example, stores an array of items, and setting SelectedIndex selects one of those items, which is then obtainable from SelectedItem. So, if a ListBox contains the MonthNames array, and SelectedIndex is set to the Month property of a DateTime object, then SelectedItem is the month name.

The TodaysDate.xaml file illustrates this technique with several TextBlock elements that format the current date. Here's a listing of the program:

In the Resources section the Framework element with a key of "datetime" obtains the current DateTime once, to be used throughout the rest of the program. The TransformGroup that follows effectively subtracts 1 from the Month property. The ListBox stores the MonthNames array and the SelectedIndex is the zero-based month.

The series of TextBlock elements display the parts of the date. The DayOfWeek property is an enumeration and can be used directly. The third TextBlock element displays the name of the month with a simple binding to the SelectedItem property of the ListBox.