Windows Store App: Creating User Control using XAML and C#

Posted by: Mahesh Sabnis , on 8/16/2013, in Category Windows Store Apps
Views: 77347
Abstract: This article talks about creating custom UserControls in Windows Store Apps using XAML & C#

The Windows 8 Store Apps platform opens up new avenues for all types of native client apps. Starting with Line of Business applications all the way to games, the new full screen, touch centric experience is rich and expressive. Needless to say the one thing that is really important for these apps is the UI.

If you are using XAML + C# for developing Windows Store Apps, then using XAML features e.g. DataBinding, DataTemplate etc. come in handy for rapidly building expressive apps. The out of box component set has controls like the Content Control, Panel Control and Items Controls that help build complex UI quickly and easily. But in some cases, utility UI controls need to be created. These UI controls are reusable both from UI and functionality perspective. Today we’ll see how we can build a custom XAML control for Windows Store Apps.

 

Key Considerations for the User Control before starting

But before creating User Controls or Custom controls, you need to decide upon the following things:

  1. What is the use of these controls?
  2. What is the look and feel of these controls?
  3. What and when the data is exposed to the consumer
  4. What data is accepted by these controls from its consumer?

These questions help in deciding the following:

  1. Decide the business logic for the control.
  2. Finalize the API that the control will expose including public properties and events.
  3. Design the look and feel of the control.

For XAML based Windows Apps, we can create dependency properties to expose data for end users and routed events for bubbling up actions.

In Windows Store Apps, for user and custom controls, we can define custom dependency property for data binding and communication, but we cannot define custom routed events because WinRT does not have an EventManager class available publicly. However, as we can work around these limitations as we will see shortly. Let’s get started.

Building the User Control

Today we will create a color palette user control. This will present user with a list of Brushes and a preview of the brush color at runtime. It will expose the color property that can then be used by the application as required (maybe setup the theme or just set color of some component).

Step 1: Open Visual Studio 2012 and create a new Windows Store App, name it as ‘CustomControlsHarness’. This will be the project where we use our custom Control.

harness-project

Step 2: Since we want our Custom Control to be an independent, reusable component we’ll add another project to the solution called ‘CustomControls’ using the ‘Class Library’ template.

custom-controls-project

Step 3: In the CustomControls project we’ll rename the default Class1.cs to ColorPickerBrush.cs and add two properties ColorName and ColorBrush.

public sealed class ColorPickerBrush
{
public string ColorName { get; set; }
public Brush ColorBrush { get; set; }
}

Step 4: In the same project add a new UserControl, and name it ‘CustomColorPicker.xaml’.

new-custom-picker-control

In the XAML we add a ListBox and DataTemplate that will be used for listing available colors.

<UserControl.Resources>
<DataTemplate x:Key="colorTemplate">
  <StackPanel Orientation="Horizontal">
   <TextBlock Width="100" Text="{Binding ColorName}"></TextBlock>
   <Rectangle Width="100" Fill="{Binding ColorBrush}"></Rectangle>
  </StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid>
<ListBox x:Name="lstColorPalette" ItemsSource="{Binding Colors}"
  ItemTemplate="{StaticResource colorTemplate}" />
</Grid>

Step 5: Next, in the code behind add the following code. It adds a Colors property, a SelectedColor dependency property and a ColorSelectedEvent EventHandler delegate.

/// <summary>
/// The property store the List of colors.
/// </summary>
public List<ColorPickerBrush> Colors { get; set; }

/// <summary>
/// The dependency Property
/// This will be used to exposed the selected color
/// from the ListBox
/// </summary>
public Brush SelectedColor
{
    get { return (Brush)GetValue(SelectedColorProperty); }
    set { SetValue(SelectedColorProperty, value); }
}
// Using a DependencyProperty as the backing store for SelectedColor.
//This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedColorProperty =
DependencyProperty.Register("SelectedColor", typeof(Brush),
typeof(CustomColorPicker), new PropertyMetadata(0));

/// <summary>
/// The Event which will be subscribed by the consumer
/// </summary>
public event EventHandler ColorSelectedEvent;

The dependency property is used to expose the selected color to the consumer application. Since the Windows Store Apps does not provide feature of the custom routed event, the event is declared using EventHandler delegate. This will be handled when a color from the ListBox is selected.

Step 6: Add the following code in the loaded event of the UserControl:

/// <summary>
/// The below implementation will do the below things:
/// 1. Get the Colors class Type
/// 2. Read Runtime properties from the Colors type
/// 3. Read each property id convert it into Color structure
/// 4. Put the colors in the Colors List
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    Colors = new List<ColorPickerBrush>();
    //1
    Type type = typeof(Windows.UI.Colors);
    //2
    PropertyInfo[] Properties =
     type.GetRuntimeProperties().ToArray<PropertyInfo>();
    //3
    foreach (var item in Properties)
    {
        string s = item.Name;
        Color c = (Color)item.GetValue(null, null);
        //4
        Colors.Add(new ColorPickerBrush()
        {
            ColorName = item.Name,
            ColorBrush = new SolidColorBrush(c)
        });
    }
    this.DataContext = this;
}

The above code makes use of the Colors class under Windows.UI namespace. The Color class contains a list of Properties each returning a particular color. The above code reads the Type and extracts all the properties from. Next it loops through each of these properties and stores them into our Colors collection by converting them into a ColorPickerBrush object.

Step 7: Next we add a SelectionChanged event handler for the lstColorPalette and add the following code for the handler:

/// <summary>
/// Get the selected item from the ListBox and assign it to
/// the SelectedColor dependency property and the event is
/// raised.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void private void lstColorPalette_SelectionChanged(objectsender SelectionChangedEventArgs e)
{
    ColorPickerBrush objColor =(ColorPickerBrush) lstColorPalette.SelectedItem;
            if (ColorSelectedEvent!=null)
            {
                SelectedColor = objColor.ColorBrush;
                ColorSelectedEvent(this, EventArgs.Empty);
            }
        }
}

The above code gets the selected color from the ListBox and assigns it to the publicly available SelectedColor dependency property. The ColorSelectedEvent is then raised so that any end user can subscribe to it and respond appropriately.

This pretty much covers our Custom Control. Let’s use it now.

Using our CustomControl

To use the custom control we must refer to it in our harness Project, so we add the project reference from CustomControls to CustomControlsHarness

win-store-custom-control-reference

Build the entire solution once.

Open MainPage.xaml in the XAML Designer, in the ToolBox you should see a new section for our CustomControls project with one control CustomColorPicker.

custom-controls-in-toolbox

Step 8: Drag-drop the CustomColorPicker control on to the MainPage.xaml designer and align it appropriately:

color-picker-in-designer

<Grid x:Name="BackgroundGrid" Background="{StaticResource
ApplicationPageBackgroundThemeBrush}">
<CustomControls:CustomColorPicker x:Name="ThemeColorPicker"
  HorizontalAlignment="Left"
  Margin="110,110,0,110"
  Width="226" />
</Grid>

We’ve named our container grid BackgroundGrid. Since changing the ApplicationPageBackgroundThemeBrush is rather tricky, we’ll simply change the background of our container control that is the BackgroundGrid.

Note: The user control is prefixed using ‘CustomControls’ which is the namespace that got automatically registered in the MainPage.xaml when we drag-and-dropped it.xmlns:CustomControls="using:CustomControls"

Select the CustomColorPicker in the XAML Designer and use the Property Pane to add a handler for the ColorSelectedEvent.

add-event-handler

The implementation of the event handler is trivial as we can see below, we simply set our container grid’s Background property to the SelectedColor of our custom component

/// <summary>
/// The method will be executed when the
/// color from the UserControl is selected. The color is then
/// assigned to the Background property of the BackgroundGrid
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CustomColorPicker_ColorSelectedEvent(object sender, EventArgs e)
{
BackgroundGrid.Background = ThemeColorPicker.SelectedColor;
}

That’s a wrap from the code perspective. Demo time!

Demo

I’ve set the project to run in the Simulator. Run the application, you will get the CustomColorPicker with Color information (Name and Brush) in it. Select any color from it, the selected color will be applied to the Application’s background. Below is a collage of 4 screenshots I took on the simulator

final-output-collage

Conclusion

It’s easy to build UI components as custom UserControls in Windows Store Apps. Before creating the UserControl make sure that you plan for need of the UserControl for your application based upon which you will implement business logic, choose ready UI elements and declare dependency property and event.

Download the entire source code of this article (Github)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by blank on Wednesday, September 25, 2013 2:17 AM
nice
Comment posted by assas on Saturday, November 23, 2013 2:06 AM
fghfghh
Comment posted by nasir on Tuesday, December 3, 2013 11:09 AM
Thanks
((▄▀▄ <a href="http://programmingexercises.blogspot.com/">Programming Exercises</a>▄▀▄))
Comment posted by Richard Ellis on Sunday, January 5, 2014 3:01 PM
Thank you for this.  I am having difficulty understanding how to use dependency properties in windows store APPS.  This helped a great deal.  It ran properly from the supplied Git.  I was trying to use in VS2013 as a windows store 8.1 APP an I could not get it to work.  I must have done something incorrectly, the APP compiles without error but the control is invisible.  I suspect 8.1 treats something differently but I have no Idea what it is.  
Comment posted by Richard Ellis on Sunday, January 5, 2014 5:15 PM
I found the problem!  In step 7 I believe the incorrect Code Segment is included.  The event handler code is
private void lstColorPalette_SelectionChanged(objectsender SelectionChangedEventArgs e)
{
    ColorPickerBrush objColor =(ColorPickerBrush) lstColorPalette.SelectedItem;
            if (ColorSelectedEvent!=null)
            {
                SelectedColor = objColor.ColorBrush;
                ColorSelectedEvent(this, EventArgs.Empty);
            }
        }

Oh my the formatting is bad, hopefully folks can save themseleves some time the correct code is inthe Git
Comment posted by Motre on Thursday, February 6, 2014 9:46 PM
Yes, Richard Ellis is correct.  The code in step 7 is the event handling code (repeated just before the demo screen shots section) rather than the event raising code.

I also found all of this very helpful, especially with regard to referencing a separate in order to get custom controls to show up in the toolbox!
Comment posted by Motre on Thursday, February 6, 2014 9:47 PM
Also, there is a typo in commented code - "Colots" instead of "Colors"
Comment posted by Aamna on Friday, May 30, 2014 7:34 AM
this code is not working in Windows 8.1 store apps. Could anyone tell me plz that this code is supported in windows 8.1 apps or not by using visual studio 2013?

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook