Sep 27, 2009

Inherit User Control in Silverlight

Inheriting a user control is very common across winforms and web controls. Doing the same in Silverlight requires certain addtional steps and tweaks.

Our goal here is to create a variant of the DatePicker control that comes as part of Silverlight toolkit. Let's call it DatePicker2. I am going to create a modified version of datepicker that would display a watermark text and also disable user from typing into the text box.

Step 1:
Create a silverlight class library project

Step 2:
Add a new Silverlight user control to the project. The control XAML code will look like this:
< Usercontrol
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300"
>
< Grid x:Name="LayoutRoot" Background="White">
< /Grid>
< /Usercontrol>
Step 3:
Add a namespace declaration for the DatePicker control. Let's call it "myctl".
Rename the Usercontrol to "myCtl:DatePicker" to inherit the control.
The modified XAML code will look like this:
< myCtl:DatePicker x:Class="MyControls.DatePicker2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:myCtl="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
Width="400" Height="300"
>
< Grid x:Name="LayoutRoot" Background="White">
< /Grid>
< /myCtl:DatePicker>
Step 4:
Switch to view the code.
Add an override for OnApplyTemplate method of the base UserControl from which DatePicker is already inherited. Add the code to display watermark text and disable the text box. With the changes, the code will look this:
namespace MyControls
{
public partial class DatePicker2 : DatePicker
{
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
DatePickerTextBox box = base.GetTemplateChild("TextBox") as DatePickerTextBox;
box.Watermark = "to enter a date click this icon -->";
box.IsEnabled = false;
}
}
}
Step 5:
Make sure to add the "System.Windows.Controls" assembly from Silverlight toolkit.
Lastly, do the following steps on the news added DatePicker2 XAML file.

1. Right-click the file in “Solution Explorer”.

2. Change the “Build Action” to “Resource”.

3. Save the project and rebuild.

Step 6:
Add the DatePicker2 control to a test XAML page and test it out!

Reblog this post [with Zemanta]

No comments:

Post a Comment