PETZOLD BOOK BLOG

Charles Petzold on writing books, reading books, and exercising the internal UTM


Recent Entries
< PreviousBrowse the ArchivesNext >
Subscribe to the RSS Feed

Formatting Text Output in XAML

March 31, 2006
New York City

I've recently discussed how to use XAML to display static properties interspersed with text (in this case static properties of the System.Environment class), and also how to use .NET text-formatting strings in XAML for single items, specifically DateTime objects.

It's also possible — with a little help from C# code, of course — to embed a formatting string into XAML to display multiple formatted objects. This is done through a MultiBinding, which is a binding commonly used to consolidate multiple binding sources into one target. (The MultiBinding documentation suggests that it be used to meld red, green, and blue values into a Color object, and my book will have an example of that.) A MultiBinding requires a class that implements the IMultiValueConverter interface. The Convert method in this class gets an array of objects (these are the binding sources) and an optional parameter that the method obtains through the ConvertParameter attribute in the MultiBinding element.

The FormattedMultiTextConverter.cs file contains a class that implements the IMultiValueConverter interface with a trivial Convert method that assumes the ConvertParameter to be a .NET formatting string, and passes both that and the array of binding source objects to String.Format.

The EnvironmentInfo2Window.xaml file uses that conversion class to display static properties of the Environment class:

Notice that the formatting string is broken into multiple lines and left aligned to avoid a lot of unwanted white space. Notice also that I broke the second and later lines so they begin with line feed characters, again to avoid unwanted white space.

The EnvironmentInfo2App.xaml file and EnvironmentInfo2.csproj projects file are necessary to compile the program in Visual Studio.


Recent Entries
< PreviousBrowse the ArchivesNext >
Subscribe to the RSS Feed

(c) Copyright Charles Petzold
www.charlespetzold.com