Logo
programming4us
programming4us
programming4us
programming4us
Home
programming4us
XP
programming4us
Windows Vista
programming4us
Windows 7
programming4us
Windows Azure
programming4us
Windows Server
programming4us
Windows Phone
 
Windows Phone

Items Controls : Binding to ItemsSource

- Windows 10 Product Activation Keys Free 2019 (All Versions)
- How To Bypass Torrent Connection Blocking By Your ISP
- How To Install Actual Facebook App On Kindle Fire
5/9/2011 6:32:03 PM
You’ve seen how to fill an items control through code or with a list in XAML. You can also set the items using the ItemsSource property defined by ItemsControl. The ItemsSource property is of type IEnumerable so you can pretty much use any collection type, including a simple array. However, if you’re dealing with a collection where items can be added or removed dynamically, then it is very common to use the ObservableCollection class, which implements the INotifyCollectionChanged interface. The items control installs a handler for this event to be notified when the collection changes and then updates itself accordingly.

Let’s create a ColorPresenter class that can fill up a ListBox with the 140 standard colors (excluding Transparent) by a single binding to ItemsSource and at the same time provide properties that allows displaying these colors in a more user-friendly manner.

It remains a mystery why the Colors class in Silverlight defines only 15 static properties of type Color instead of 141. That makes the ColorPresenter class rather awkward. I already had a WPF program that used reflection on the WPF Colors class, so I adapted that to generate the color names and values that I pulled into this class. Here they are in two static arrays in the ColorPresenter class in the Petzold.Phone.Silverlight library:

Example 1. Silverlight Project: Petzold.Phone.Silverlight File: ColorPresenter.cs
using System;
using System.Text;
using System.Windows.Media;

namespace Petzold.Phone.Silverlight
{
public class ColorPresenter
{
static string[] colorNames =
{
"AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure",
"Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet",
"Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate",
"Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan",
"DarkBlue", "DarkCyan", "DarkGoldenrod", "DarkGray", "DarkGreen",
"DarkKhaki", "DarkMagenta", "DarkOliveGreen", "DarkOrange",
"DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen",
"DarkSlateBlue", "DarkSlateGray", "DarkTurquoise", "DarkViolet",
"DeepPink", "DeepSkyBlue", "DimGray", "DodgerBlue", "Firebrick",
"FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite",
"Gold", "Goldenrod", "Gray", "Green", "GreenYellow", "Honeydew",
"HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender",
"LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue",
"LightCoral", "LightCyan", "LightGoldenrodYellow", "LightGray",
"LightGreen", "LightPink", "LightSalmon", "LightSeaGreen",
"LightSkyBlue", "LightSlateGray", "LightSteelBlue", "LightYellow",
"Lime", "LimeGreen", "Linen", "Magenta", "Maroon",
"MediumAquamarine", "MediumBlue", "MediumOrchid", "MediumPurple",
"MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen",
"MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream",
"MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive",
"OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenrod",
"PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip",
"PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red",
"RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown",
"SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue",
"SlateGray", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal",
"Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White",
"WhiteSmoke", "Yellow", "YellowGreen"
};

static uint[] uintColors =
{
0xFFF0F8FF, 0xFFFAEBD7, 0xFF00FFFF, 0xFF7FFFD4, 0xFFF0FFFF,
0xFFF5F5DC, 0xFFFFE4C4, 0xFF000000, 0xFFFFEBCD, 0xFF0000FF,
0xFF8A2BE2, 0xFFA52A2A, 0xFFDEB887, 0xFF5F9EA0, 0xFF7FFF00,
0xFFD2691E, 0xFFFF7F50, 0xFF6495ED, 0xFFFFF8DC, 0xFFDC143C,
0xFF00FFFF, 0xFF00008B, 0xFF008B8B, 0xFFB8860B, 0xFFA9A9A9,
0xFF006400, 0xFFBDB76B, 0xFF8B008B, 0xFF556B2F, 0xFFFF8C00,
0xFF9932CC, 0xFF8B0000, 0xFFE9967A, 0xFF8FBC8F, 0xFF483D8B,
0xFF2F4F4F, 0xFF00CED1, 0xFF9400D3, 0xFFFF1493, 0xFF00BFFF,
0xFF696969, 0xFF1E90FF, 0xFFB22222, 0xFFFFFAF0, 0xFF228B22,
0xFFFF00FF, 0xFFDCDCDC, 0xFFF8F8FF, 0xFFFFD700, 0xFFDAA520,
0xFF808080, 0xFF008000, 0xFFADFF2F, 0xFFF0FFF0, 0xFFFF69B4,
0xFFCD5C5C, 0xFF4B0082, 0xFFFFFFF0, 0xFFF0E68C, 0xFFE6E6FA,
0xFFFFF0F5, 0xFF7CFC00, 0xFFFFFACD, 0xFFADD8E6, 0xFFF08080,
0xFFE0FFFF, 0xFFFAFAD2, 0xFFD3D3D3, 0xFF90EE90, 0xFFFFB6C1,
0xFFFFA07A, 0xFF20B2AA, 0xFF87CEFA, 0xFF778899, 0xFFB0C4DE,
0xFFFFFFE0, 0xFF00FF00, 0xFF32CD32, 0xFFFAF0E6, 0xFFFF00FF,
0xFF800000, 0xFF66CDAA, 0xFF0000CD, 0xFFBA55D3, 0xFF9370DB,
0xFF3CB371, 0xFF7B68EE, 0xFF00FA9A, 0xFF48D1CC, 0xFFC71585,
0xFF191970, 0xFFF5FFFA, 0xFFFFE4E1, 0xFFFFE4B5, 0xFFFFDEAD,
0xFF000080, 0xFFFDF5E6, 0xFF808000, 0xFF6B8E23, 0xFFFFA500,
0xFFFF4500, 0xFFDA70D6, 0xFFEEE8AA, 0xFF98FB98, 0xFFAFEEEE,
0xFFDB7093, 0xFFFFEFD5, 0xFFFFDAB9, 0xFFCD853F, 0xFFFFC0CB,
0xFFDDA0DD, 0xFFB0E0E6, 0xFF800080, 0xFFFF0000, 0xFFBC8F8F,
0xFF4169E1, 0xFF8B4513, 0xFFFA8072, 0xFFF4A460, 0xFF2E8B57,
0xFFFFF5EE, 0xFFA0522D, 0xFFC0C0C0, 0xFF87CEEB, 0xFF6A5ACD,
0xFF708090, 0xFFFFFAFA, 0xFF00FF7F, 0xFF4682B4, 0xFFD2B48C,
0xFF008080, 0xFFD8BFD8, 0xFFFF6347, 0xFF40E0D0, 0xFFEE82EE,
0xFFF5DEB3, 0xFFFFFFFF, 0xFFF5F5F5, 0xFFFFFF00, 0xFF9ACD32
};

// Static constructor
static ColorPresenter()
{
Colors = new ColorPresenter[140];

for (int i = 0; i < 140; i++)
{

// Break down the color into components
byte A = (byte)((uintColors[i] & 0xFF000000) >> 24);
byte R = (byte)((uintColors[i] & 0x00FF0000) >> 16);
byte G = (byte)((uintColors[i] & 0x0000FF00) >> 8);
byte B = (byte)((uintColors[i] & 0x000000FF) >> 0);

// Create a display name for the color
StringBuilder builder = new StringBuilder();

foreach (char ch in colorNames[i])
{
if (builder.Length == 0 || Char.IsLower(ch))
builder.Append(ch);
else
{
builder.Append(' ');
builder.Append(ch);
}
}

// Create a ColorPresenter for each color
ColorPresenter clrPresenter = new ColorPresenter();
clrPresenter.Color = Color.FromArgb(A, R, G, B);
clrPresenter.Name = colorNames[i];
clrPresenter.DisplayName = builder.ToString();
clrPresenter.Brush = new SolidColorBrush(clrPresenter.Color);

// Add it to the static array
Colors[i] = clrPresenter;
}
}

public static ColorPresenter[] Colors { protected set; get; }

public Color Color { protected set; get; }

public string Name { protected set; get; }

public string DisplayName { protected set; get; }

public Brush Brush { protected set; get; }

public override string ToString()
{
return Name;
}
}
}


Towards the bottom you’ll see the public instance properties that ColorPresenter exposes: Color of type Color, Brush of type Brush, but also Name of type string, and DisplayName. The DisplayName property converts the single-word camel-cased standard names to multiple words. For example “AliceBlue” becomes “Alice Blue”.

ColorPresenter also exposes a public static property named Colors. This is an array of all 140 ColorPresenter objects. This array and all its contents are created in the class’s static constructor.

If you were using ColorPresenter solely in code, you wouldn’t need to create any additional instances of the class. You could simply access the static ColorPresenter.Colors property to get all 140 ColorPresenter objects.

However, Silverlight doesn’t provide a way to access a static property in XAML without instantiating the class containing that property, so the ColorPresenterDemo project includes the ColorPresenter class in its Resources collection:

Example 2. Silverlight Project: ColorPresenterDemo File: MainPage.xaml (excerpt)
<phone:PhoneApplicationPage.Resources>
<petzold:ColorPresenter x:Key="colorPresenter" />
<petzold:StringFormatConverter x:Key="stringFormat" />
</phone:PhoneApplicationPage.Resources>

The instance of ColorPresenter created in the XAML file will not have any useful instance properties, but the program only needs the static Colors property.

The content Grid has just two rows: one for the ListBox and one for a TextBlock with bindings to the ListBox. Notice the ItemsSource property of the ListBox bound to the Colors property of the ColorPresenter resource. With this binding, the ListBox is filled with 140 objects of type ColorPresenter so the DataTemplate can have bindings to the DisplayName and Color properties of that class:

Example 3. Silverlight Project: ColorPresenterDemo File: MainPage.xaml (excerpt)
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>

<ListBox Grid.Row="0"
Name="listBox"
ItemsSource="{Binding Source={StaticResource colorPresenter},
Path=Colors}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>

<Rectangle Grid.Column="0"
Fill="{Binding Brush}"
Width="72" Height="48"
Margin="2 2 6 2" />

<StackPanel Grid.Column="1"
Orientation="Horizontal"
VerticalAlignment="Center">

<TextBlock Text="{Binding DisplayName}" />

<TextBlock Text="{Binding Color.R,
Converter={StaticResource stringFormat},
ConverterParameter=' ({0:X2}'}" />

<TextBlock Text="{Binding Color.G,
Converter={StaticResource stringFormat},
ConverterParameter='-{0:X2}'}" />

<TextBlock Text="{Binding Color.B,
Converter={StaticResource stringFormat},
ConverterParameter='-{0:X2})'}" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

<TextBlock Grid.Row="1"
FontSize="{StaticResource PhoneFontSizeExtraLarge}"
HorizontalAlignment="Center"
Margin="12"

Text="{Binding ElementName=listBox,
Path=SelectedItem.DisplayName}"

Foreground="{Binding ElementName=listBox,
Path=SelectedItem.Brush}" />
</Grid>


The SelectedItem property is also of type ColorPresenter, so the TextBlock can reference properties of ColorPresenter for the bindings to Text and Foreground:



Putting these color names in your color-selection user interface is something you might consider. Familiarity with these names goes beyond programmers to anyone who’s worked with colors in HTML, so the more sophisticated users of your application might have a very positive response to seeing these actual names on the screen.

Other -----------------
- Items Controls : ListBox Selection
- Items Controls : Customizing Item Displays
- Items Controls and Visual Trees
- The Two Templates : Custom Controls
- The Two Templates : The Ever-Handy Thumb
- The Two Templates : Variations on the Slider
- The Two Templates : Custom Controls in a Library
- The Two Templates : Sharing and Reusing Styles and Templates
- The Two Templates : The Visual State Manager
- The Two Templates : ControlTemplate Basics
 
 
Top 10
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
Popular tags
Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Biztalk Exchange Server Microsoft LynC Server Microsoft Dynamic Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 windows Phone 7 windows Phone 8
programming4us programming4us
Celebrity Style, Fashion Trends, Beauty and Makeup Tips.
 
programming4us
Windows Vista
programming4us
Windows 7
programming4us
Windows Azure
programming4us
Windows Server