In this article we will discuss how to make color picker using System.Windows.Media.Colors. The color picker made using System.Windows.Media.Colors will contain following colors Black, Blue, Brown, Cyan, DarkGray, Gray, Green, LightGray, Magenta, Orange, Purple, Red, Transparent, White and Yellow.

Let's see how to create color picker with above colors.
ListBox, WrapPanel and Button will be use to demonstrate the example of color picker. Refer my previous article Part 47 - Windows Phone 7 - WrapPanel to know about wrappanel.
Download Silverlight Windows Phone Toolkit to use WrapPanel.
Step 1: Create a silverlight for Windows Phone project.
Step 2: Add reference of Microsoft.Phone.Controls.Toolkit.dll
Step 3: Add namespace of Microsoft.Phone.Controls.Toolkit in MainPage.xaml.
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
Step 4: Place a listbox containing WrapPanel and Button inside ContentPanel of MainPage.xaml.
<ListBox x:Name="listBox"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <toolkit:WrapPanel FlowDirection="LeftToRight" ItemWidth="100" ItemHeight="100"/> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.ItemTemplate> <DataTemplate> <Button Click="btn_Click" BorderThickness="1" VerticalAlignment="Center" HorizontalAlignment="Center" Background="{Binding Color}" Margin="-10,-10,0,0" Height="100" Width="100" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
Step 5: Create a class ColorItem with property Colo
public class ColorItem { public SolidColorBrush Color { get; set; } }
Step 6: Now create a List of ColorItem and define two variables of ColorItem and SolidColorBrush. To get all the colors from System.Window.Media.Colors typeof(Colors).GetProperties() will be used which returns collection of Color. All the returned color will be added in the List and at last the list will be binded to listbox.
List<ColorItem> lst = new List<ColorItem>(); ColorItem ci; SolidColorBrush scb;
foreach (var color in typeof(Colors).GetProperties()) { ci = new ColorItem(); scb = new SolidColorBrush(); scb.Color = (Color)color.GetValue(null, null); ci.Color = scb; lst.Add(ci); }
this.listBox.ItemsSource = lst;
Step 7: Add btn_Click event handler which will change the pick the color and change the ContentPanel backgroudn color.
private void btn_Click(object sender, RoutedEventArgs e) { Button button = (Button)sender; ContentPanel.Background = button.Background; }
Now run the application and click on any of the button, the contenpanel color will be changed with the selected color.

This ends the article of color picker with System.Windows.Media.Colors in Windows Phone 7.
|