A Custom Control in Silverlight 4

debal_saha-9451
Posted by in Silverlight category on for Intermediate level | Points: 250 | Views : 25724 red flag
Rating: 4 out of 5  
 2 vote(s)

In Silverlight Projects I have seen using Custom Controls are vast. Now when I was studying about CustomControl I learned a lots of things on that . But in searching in internet there also various site regarding on that . MSDN is one of them good resources and others site are also available describing the CustomControl good enough. Whatever I have seen Custom Controls are like Textboxes, Text Blocks, Combo boxes, DatePickes etc . Now it is a little bit confusing that when Microsoft is providing So many controls & u can easily get it in ur ToolBox of ur VisualStudio2010 Silverlight Projects. So what is the meaning of CustomControls & I have also written the example of customcontrols like TextBoxes, DatePicker….. Well , we are going little deep of its basics.


 Download source code for A Custom Control in Silverlight 4

What is CustomControl?

Generally speaking a CustomControl is a loosly coupled control usually defined in a class, which derives from  an existing control and extends it functionality in different way. Though CustomControl  are defined within in a Class But , the visual effects (I mean the UI of custom Control) generally defined in Resource Dictionary inside the resource file . This makes it little complex. But, u have a freedom to make our desired control as we want.

What are the benefits of CustomControl?

CustomControls are reusable controls. Once u creates a custom Control u can simply use it in different projects by simply add the assembly in the projects. Yes , in our Visual Studio toolbox  what we do Simply Drag & drop our controls from this and use this as per requirement. But generally u can’t able to see ur newly make customcontrol in toolbox for that there need to do some additional steps . I’m skipping this at this moment . Not only CustomControl is a reusable controls but also they can be skinnable,themable in any projects.

One thing also is that we make our CustomControl because of sometimes ur Silverlight common control doesn’t cover our specific requirements to apply in Projects.

The buttons, Textboxes, Comboxes …. etc even usercontrol are also customcontrol. Usually a CustomControl is inherit from System.Windows.Controls.Control or  System.Windows.Controls.ItemsControl or System.Windows.Controls.ContentControl etc.

  • Controls : Represents the base class for UI elements that use a ControlTemplate to define their appearance.
  •  ItemsControl : Represents a control that can be used to present a collection of items.
  •  ContentControl : Represents a control with a single piece of content. Controls such as Button, CheckBox, and ScrollViewer directly or indirectly inherit from this class.

When to use CustomControl  ?

Now this is good idea when should I use CustomControl . I also write some description on it but  have  a look for clear idea.

  •  Use CustomControl   when you think that ur basic controls doesn’t provide much more functionality as u want , then pl make a customcontrol for urself.
  •  When  u want to apply theme to ur control ,use CustomControl  .
  • Suppose u have more than two projects in ur Silverlight Appliclications & using same components so it is better idea to make them a CustomControl  instead of  combinging or grouping them in UI and write code for multiple times .
  •  Use CustomControl   when u think to make a completely new control or a specific version of a control.

OK…I hope this gives a basic idea where & when to use CustomControl but may be there some specific requirements to u to make a Custom Control.

For understanding other flexibility of CustomControl u need to know about Usercontrol. And basic difference between CustomControl  & UserControls . Let’s see….

What is a user Control?

Use UserControl when u needs a fixed content control which will encapsulate related existing control and provides its own logics.  Also when you separate ur basic functionality of UI page(view page ) in to some smaller , manageable pieces of logics with reusability then use User Control. In Silverlight , generally we put the User Control as a root of element in application.

Now,  we getting confusing why and what is the relation between CustomControl & Usercontrol then Pl look at this table.

 

Difference between UserControl & Custom Control

UserControls CustomControl
UserControl is easier to create. CustomControl   Is  harder to create
UserControl defines its User Interface in the plain xaml file.
CustomControl     defines it's User Interface in ResourceDictionary generally called it generic.xaml
User control also can be added in your toolbox. It is a tightly coupled control with respect to your code .
CustomControl     Full Toolbbox Support .It is a loosely coupled control with respect to your code.
Once u use UserControl in UI it is fixed can’t be changed in ur referenced projects. CustomControl  Gives much more flexibility & u are freedom to use(can be changed) it in ur any referenced Projects.
UserControl derives from System.Windows.Controls.UserControl. CustomControl    Derives from System.Windows.Controls.Control Class ,
UserControls can’t be, themeable , or skinnable(only child controls of usercontrol are skinnable). CustomControl    Canbe Themeable,Skinnable
UserControl is a set of Controls CustomControl  generally  Defines in a single control

Theory is going much more . If u interested to learn more pl visit MSDN site or in Google. OK first create a projects .But one thing is note that u need to use Expression Blend 4. Though it is not mandatory for creating Custom Control  but I use this in my simple project so it is require in here.  ……..but I also use Visual Studio. If U don’t know how to create Silverlight application just look in Google , it is very simple . I skip this image in this article. Ok , first see the below two images which describes what we are going to make and what will be our desired custom control.

Pic-1

This is the front side of our newly make custom control. If u click on the Red Flip button then it will rotate as well as also you can see the back side of our control. See pic -2 . I have got the idea to make it after seeing my voter id card. Let’s build it .

Pic-2

Before going in that be sure Your machine have all the software that are necessary to built Silverlight Application. Or Pl visit http://silverlight.net/getstarted/

1. Open VisualStudio 2010  & create a new SilverLight 4 Application in & name it what u wish. I give it SilverlightCustomControl.

2. Now Right Click on ur VisualStudio Solution & select Add New Project . Select SilverlightClassLibrary and name it CreateControl. Choose Silverlight 4 Version.

3. Delete the Class1.cs file from ur newly create Projects. Just Select the CreateControl Projects. Right click on it and add new item. Select SilverlightTemplate Control and give the name it FlipPanelControl.
U will see that VisualStudio has been create a new folder in ur project in the nameof “Theme” and under this folder there is a “generic.xaml” page and other is ur class name is “FlippanelControl.cs”

See the Image .

Pic-3

4.If u don’t find ur generic.xaml but can able to get ur FlippanelControl.cs (I have suffered that because of visual Studio internal error) then Just right click on the project(CreateControl) & add a new folder give it name Theme and add a new Item SilverlightResourceDictionary(See in the above Pic-3 Image U will find Silverlight Resource Dictionary) give it name generic.xaml. Please skip this step if u get successfully Theme folder and generic.xaml page after  step 3. So finaly ur SolutionExplorer looks like  this pic -4.

Pic-4

5. Now, ur project is ready . It is time to make our control.

6. I have already told that to make CustomControl we have to do work in the Resource File . In resource file u have to make the style for the control. But before that we need to back in some theory . ? So what is that ? Actually , all the default CustomControl are lookless. The file generic.xaml contains the UI of ur CustomControl. To make the Style of our CustomControl we need to do work with the ControlTemplate.

 What is ControlTemplate?

Template allows u to change the Visual face of any Common Control. A ControlTemplate is nothing more than  a resource, usually defined in the style, which allows u to specify the way a control is displayed in Visual Tree.

If u familiar with styles in Silverlight then it will easy to u understand.  Although , styles are different from Template. See the below Table.

 

Difference between Styles & Template

Styles Templates
Styles can be used with any Silverlight Elements that is derived from Framework Element . Templates   Used only those elements that inherit from the Control class in the System.Windows.Control namespace.
By using Styles , u can modify the default values of properties of the control to which the style is applied . By using  Templates u can modify the structure of the Control to which the Template is applied.
The Properties values in styles can be Overridden by the values that are set on the control itself when it is drawn in the artboard . Templates      Values can’t be overridden by the values that are set on the control itself when it is drawn on the artboard .But , using Template Binding the property’s  value can set of a template according to the values of a properties of the control when it is drawn on the artboard.
Within a style u can only modify pre-existing properties of the Control. When u  Modify with Template u can access to more parts of control then styles.
Using Styles u can only specify the default behavior of a control. By  using   Trigger u can specify the behavior of any new & existing parts in a Template.

I hope this can give a basic Idea. By creating template we will know more on this. Let’s do it …..

7. Now it is time to open our generic.xaml   file which is under Theme folder . Write the namespace of ur CustomControl in the file.

xmlns:local="clr-namespace:CreateControl;assembly=CreateControl"

This is because ur CustomControl may be applied in other Projects/Application . Now design the style for ur control . To make the design of ur CustomControl need to write the line of code :

<Style TargetType="local:FlipPanelControl">

<Setter Property="Template">

<Setter.Value>

<ControlTemplate TargetType="local:FlipPanelControl">

……

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>

The first line is containing one property TargetType which indicates that in which control of the Silverlight Element u want to apply style. If it would button then u need to write  TargetType=”Button”. As I told that The ControlTemplate class enables you to redefine the way a Control looks. So here the code that display & same use of TargetType . Now go further……

8. Now put a grid inside the Control Template. To do work with the States of our Custom Control we need to know about VisualStateManager. Silverlight provides u to manage a control what it should be liked in a certain state (For e.g. A button can in a Pressed or disable state) is known as a VisualStateManager. A Visual State Manager is an element that manages the states and Transaction between states. This changes can do two different types of effects.  The First is know Statebased effect & other is known as Transitioning effect .  Last one thing is very important: remember when a control enters a VisualState the storyboard associated with the visualstate begins.

So What is a Storyboard?

A Storyboard is a simple way to animate dependency properties of an object in Silverlight. Storyboard has a strong capability to add RIA by adding interactivity & movement. Storyboards are generally contains in xaml but as well as in code also it can be done.  Remember onething Silverlight Animations are timeline objects where Flash and others are different from it.

Next follow the Code .

<ControlTemplate TargetType="local:FlipPanelControl">

<Grid>

<VisualStateManager.VisualStateGroups>

<VisualStateGroup x:Name="ViewState">

<VisualState x:Name="Normal"/>

<VisualState x:Name="Flipped"/>

</VisualStateGroup>

</VisualStateManager.VisualStateGroups>

</Grid>

</ControlTemplate>

9. Look at the code . There is a new item VisualStatesGroup which indicates that u can only create transitions between states that belong to the same group because a control can be in Multiple states as long as those states belong to different groups. We will see the storyboard latter.

10. Just make a simple Row and columns of the Grid . I give the size of column * which means that the inner contents of grid will be auto on base of customcontrol’s size. Add two Border in the name of “FontContent” & “backContent” respectively .

<border x:name="FontBorder" background="{TemplateBinding Background}" borderbrush="{TemplateBinding BorderBrush}"borderthickness="{TemplateBinding BorderThickness}" rendertransformorigin="0.5,0.5"

grid.columnspan="4">

</border>

11. Look the code one new thing is the TemplateBinding . The Template Binding is a special type of databinding used in a controlTemplate . The Databinding uses the control to which the ControlTemplate is applied  as its datasource .The datasource is identified as a specific property within that control. This property is referenced by name when u create a TemplateBinding. So, in this code u see that TemplateBinding is using background, borderbrush etc….. of the CustomControl & these Property values are used by the Border .

12. Now add the assembly of Create Control   class in ur Main Projects(In my Projects it is Silverlight4CustomControl) just right click on the Silverlight4CustomControl Project & choose add reference . Now find out the Project createControl , select it & click add . See pic -5 & pic -6
Pic-5

13. Our default CustomControl is ready.

Pic-6

14. Now open the FlipPanelControl.cs file, which is in the CreateControl Projects. Write down the code in the constructor of our FlipPanelControl.cs Class.

this.DefaultStyleKey = typeof(FlipPanelControl);

Here the defaultStyleKey Property indicates that the type that is used to lookup the style. This Property is used to pick up the default style from the generic.xaml. See the target type of . This is only use in those cases whenever u want to make a totally different style & different control template , then u need to add the style using the  target type of the new  CustomControl class and set the Defaultstylekey property accordingly to it . Otherwise , if u want to create a customized control with just only additional functionality then u can save the trouble of making new style .

15. Add parts & state in the ur Control. Look parts are the named element that a control expects to find in a Template. States are the name animations that are applied at specific Times .  In our control two states are required one is Normal & other is Flipped . Using TemplateVisualState attribute Class specify that  a control can be in a certain state and that a state is expected in the control’s  ControlTemplate. The Properties of the TemplateVisualState Attribute Class’s ares GroupName & Name . 
Name specify that which states are the control is adding in TemplateVisualState Attribute class. And the GroupName property is sets the name of the group that the state belongs to . See the code :

[TemplateVisualState(Name = "Normal", GroupName = "ViewStates")]

[TemplateVisualState(Name = "Flipped", GroupName = "ViewStates")]

16. To make one control it may be requirement of another control.  For example: we have seen datepicker . Actually this consists of one textbox where the selected date are displayed & one is the dropdown button through click it the calendar is open. So, in our this CustomControl we need one button & its responsibility is to filp the control from normal position. When a control need to indicate that it uses a specific part then it need to use TemplatePart Attribute. The TemplatePart  is associated with Name  & Typeof property . Where name  describes the pre-defined name of the part. And Type property sets the type of the named part that this Attribute is identifying .

In our CustomControl we are going to use toogle button . For more about this pl refer in MSDN. Toggle button is a clickable button that can be in one of two states . In our Sample the button will be two states in one is Normal & other is Flipped mode .

[TemplatePart(Name = "FlipButton", Type = typeof(ToggleButton))]

Remember we need to use using System.Windows.Controls.Primitives;
Namespace for togglebutton.

17.  In this step we have to make properties of our CustomControl that the control will be used . lets do it .  As we are doing with the properties in a Silverlight element, you should use dependency properties. Most of the properties in Silverlight elements are deal with dependency properties . For e.g., Text property of the Textblock , the content property of the Button ….etc are dependency property. Why we need to use dependency property ? What is the difference between normal property & dependency property ?

Ok, dependency property is a property that can be set directly by ur code or by silverlight  services i.e. databinding, animations, styles. As the name mentioned dependency property is a property of an element that depends on a number of property providers outside of the element is called dependency property.  The dependency property actually introduced in WPF. See the basic difference between dependency property & normal property:

DependencyProperty         CLR Property
Dependency Property is a property which register another property, It is depend on not itself but depend on (for e.g.  xaml binding ) external inputs . CLR Property   Is a Classic .NET Class property. It is a normal property Which is nothing but a cross connection between fields & methods.
Dependency Property is set to enable declarative code to alter the properties of an object which reduces the data requirements by providing a more powerful notification system regarding the change of data in a very specific way CLR Property        Is the normal property which doesn’t have more functionality like dependency property. It is  wrapped only with get and set  arrangement to be able to retrieve and update a private member.
DependencyProperty.Register() method contain the Propertymetadata objects that stores the default value of the property. It may be also null. CLR Property Need not to carry any default value .
DependencyProperty should be register to  the normal CLR property  with Register() method by passing the property field that you use to store the data. CLR property  Need to not to register with any property, it is straight forward.
Dependency Property can also contain the property changes notification . Using the CallBack() while registering the property can send the notification to user when the value has been chaged . CLR Property    Don’t have any Notification  system.

How to define dependency property in your code . Thanks Visual Studio snippet “Propdp” & press two times TAB the u will see that visual studio has create a code for yourself. Just u need to modify it .

I also recommend you to go much more deep in dependency property, in this article I skip much more details of it with example .  Refer  MSDN Site or in google to find better article on it . Lets go back in our CustomControl.

18. Make Some dependencyproperty for our control in the name of FrontContentProperty, BackContentProperty, IsFlipped property. Look at the code:

public static readonly DependencyProperty FrontContentProperty =

DependencyProperty.Register(

"FrontContent",

typeof(object),

typeof(FlipPanelControl),

new PropertyMetadata(null));

Before going deep in it, u should know that dependency property class is derived from the Dependency Object  . See the code, the name of the dependency property is FrontContentProperty . If u looks carefully then u first find that Public access modifier is present which describes that the property is accessible outside of the assembly.

Second look the static keyword is mentioned in the DependencyProperty. Actually, Silverlight ensures that the dependency property objects can’t be instantiated directly because the dependency property class doesn’t have any public constructor. Just select the dependency property Class & press F12. U will get the idea behind it. Hence the dependency object   can only be initialized by using static DepenecyProperty.Register() method.

Next See the ReadOnly in the code this means that once the Property will registered with the Static Constructor of the Class , it can’t be changed or re-register . Hence  it is done with ReadOnly.

DependencyProperty.Register() method takes 4 parameter in Silverlight 4.0.

Last see the dependency property in a  Class is registered with a normal .NET property in the name of “FrontContent.”

Next  see in the above code the  typeof() defines the datatype of the dependencyproperty which is  being registered. Here this is nothing but a object class. Then again see the another typeof () which describes the type that owns this property , in our example FlipPanelControl is the type that owns this property.

Last is the default property metadata, which can contain the System.Windows.PropertyChangedCallback implementation reference .  Actually, this notify the property value is changed. This metadata also contain the default value of the property. We give it null.

19. See the next code .

public Object FrontContent

{

get { return (object)this.GetValue(FrontContentProperty); }

set { this.SetValue(FrontContentProperty, value); }

}

Here, the Normal .NET property is defined as we generally used. But it is some different than normal CLR Property. Lets find out the difference. First see the return type of the property that is nothing but Object class and see this return type is same when we registered the property to Dependecy.Register() method in the first typeof().

Now the “FrontContent” is the normal property name. This is wrapped with normal get & set .  This Property Wrapper must be defined in the same class where the dependency Property has defined .But there is a difference is that in normal .NET Property we store the value in the private filed & retrieved it through get . But here look this is not . Here is two method GetValue() & SetValue() is defined .

These two methods derived from the Dependency Object Class.  Remember whenever you create this type of property wrapper you should not write any extra logic to validate values, raised events and so on…..The reason behind it , silverlight  may bypass the property wrapper and call these two methods directly.

Here I hope here the basic idea of dependency property you can get. But it is not complete information of dependency property. Follow the MSDN . There is an another special type of   dependency property in silverlight is the Attached Property.  Though the Attached Property is full – fledged dependency property. But there is also difference.  The Attached Property is applied to a class other than the one where it is defined. One good example of Attached Property is the Row & Column of Grid Class. See, you can use the Row & Column of grid class on Contained elements to defined them where should be they positioned. Another thing also remember that whenever you create this Attached Property you don’t write the property wrapper as like on the above dependency property we have done. Surprised, ? yes it is natural. But, get the point why is it? Actually, Attached Property can be set on any dependency object.

But Attached Property requires a pair of static methods that can be called to set & get the property value. These methods are same to GetValue() & SetValue() and also inherited from dependency object but their names should be SetPropertyName() & GetPropertyName(). These two method should be static. The SetPropertyName() method take two arguments . First is the element name on which you want to set the property (For Example, an object of an UIElement Class) & set the value of the property (it may be string, int etc…). For More discussion read the MSDN article.

20. Now we understand the dependency property , so it is the time to make some more dependency property . I have created three dependency property in the name of backcontentProperty, IsFlipped Property, FrontContentProperty.

21. The Next thing we have to do is that just write a simple code on our CustomControl Class. (Remember, Our CustomControl  class is FlippePanelControl.cs) . Look at the code .

public override void OnApplyTemplate()

{

base.OnApplyTemplate();

}

Just write Public override then in intellisence u  will see the OnApplyTemplate
, just press TAB two times , u will get the above code. Lets understand the meaning of this code , why we write this .

First look it is defined with Override Keyword .  So by this we can easily understand that this method has been defined previously in the base class. So , just select the OnApplyTemplate() method & press the F12 , you will see in the FrameworkElement class , it has defined. Ok,   this method is called when the control is being initialized i.e when the UI element will be displayed in application. Through this method Control needs to examined its template which may be required for it and so u require this method to Override. This is not covered we will come back soon in it after few steps .

22. Now your control is almost get ready .  So try to use it in the Mainpage.xaml page . Before that compile ur Application if u face any error try to solve it . Open MainPage.xaml. Give a reference of ur CustomControl Class. Look Pic – 7.
Pic-7

So the code is this .

xmlns:localcontrol="clr-namespace:CreateControl;assembly=CreateControl"

Now you can get your Custom control in ur xaml page . See the code .

<localcontrol:flippanelcontrol grid.column="1" height="85" borderthickness="2" />

23. Now it’s time to do work in Expression blend 4. U can install this from this site & need to follow download instruction. http://www.microsoft.com/expression/try-it/. I assumed that you have successfully installed this . If u have any installation problem pl keep patient & try to follow the Microsoft Instruction.

24. Open Expression Blend .  How ?   well  , Just select ur VS 2010 current application. See , Our Application name is Silverlight4CustomControl . In the application just select the MainPage.xaml page and right click on it .  Among the Option You will get below pic -8.
Pic-8

25. If u use first time Blend, then it may be some difficult to u to use. But we will do it step by step.  One interesting thing is to see our newly created Properties in Blend 4.  Isn’t it?  Just open Properties  tab , if you not able to find it then see in the Window tab & select it . See in the Pic -9. Now select our CustomControl (I give the name of it Panel) see the pic -10.  We need to search it in the Object Timeline Panel . If You don’t find Object and Timeline panel then just do the same as described above line & also in Pic – 9.

Pic-10

Pic-9

26.  After selecting Our Panel Custom Control just go to the properties window. Find out the miscellaneous   category. There you will find our properties that we have created. It’s so Cool
See below Pic -11.
Pic-11

27. Now going to start our journey to discovering the Panel in Blend 4. Before we doing more first need to do . Just like Properties window find out Resource . If don’t find it follow carefully the pic – 9 you will see the Resource , you should click it & see the  mark beside it . In the Resource you will find the App.xaml . Just right click on it , U will find Linked to Resourced Dictionary , select generic .xaml . look at the Pic -12.

Pic-12

28. If You successfully can do it , then open App.Xaml page you will get able to see the below code . Remember the App.xaml file should be in ur Current Project Folder . See the Pic -13

Pic-13

The Code is

<Application.Resources>

<!-- Resources scoped at the Application level should be defined here. -->

<ResourceDictionary>

<ResourceDictionary.MergedDictionaries>

<ResourceDictionary Source="/CreateControl;component/Theme/generic.xaml"/>

</ResourceDictionary.MergedDictionaries>

</ResourceDictionary>

</Application.Resources>

Your Intelligent brain may asked What is this App. Xaml ?

What is a App.Xaml?

Actually App.xaml file is used by Silverlight Application to define Your shared resources. For Example, styles of Specific controls .  The Code behind of it also handle the global application label events like Application_Startup, Application_Exit and Application_UnhandledException. You can think it like Asp.NET Global.asax file.

Suppose, If u define a of texbox  style in App.Xaml , then there is no requirement of using key , The style will automatically applied all textboxes wherever it will find the textboxes in the Whole Application. It is very interesting.

If  U look at the code then u will see the Resource Dictionary . For Beginner you may ask What is this .  So , First have to know about of that .

What is a Resource Dictionary? 

Resource Dictionary is a simple XAML document that is used to store a set of resources . Here we can store styles, other objects can be brushes, Transform & even an instances of   own classes .
Resource Dictionary is used in design time. Now again look at the code you will see the Merged Dictionary. So, What is that?

What is Merged Dictionary?

Merged Dictionary enables to you to declare the contents of resources dictionary by referencing an external file & uses the externally defined resources In the existing Framework Element. Using the Source property you can define the path of the external resources.

29. Now again come back in our blend .   We need to do work with Object & Template Panel. If you don’t find this just do the same as we did in  the Pic -9.  In Object & Timeline there you will find the LayoutRoot & under this there will be Panel, which is the name of our Custom Control. Select the panel & right click on it  go to Edit Template & then select Edit Current . See in the Pic – 14.

Pic-14

30. When you will click on the Edit Current you will find that our control will be in Edit mode. If U Click the Scoop up Button  then You will back in the Editing Scope of our Control. See Pic – 15.

Pic-15

31. Now go to Asset Option  Click on it .You will get a Search text box . Type in it Toggle Button . You will find it ( Be sure you have Silverlight 4 tools & sdk  are properly installed in your machine) .  Drag & Drop it in Your panel Control Template . If you can done this , then you will see the same as in  pic – 15. If You can’t able to do it then Simply write the code in generic.xaml as mentioned below. After this you will find the Toggle button as in Pic -15.

<ToggleButton x:Name="FlipButton"

Grid.Column="1"

Grid.Row="1" VerticalAlignment="Bottom"

Grid.ColumnSpan="2"

Height="48" Width="93"

RenderTransformOrigin="0.5,0.5">

</ToggleButton>

32. We need to make our FlipButton as like our pic -1 . So to do that we need to make a style for it . So , in Edit mode of the Panel go to select the FlipButton and then right click on it - > Select Edit Template -> Edit a copy , See Pic – 15 for clear idea. When You click  Edit a  Copy then a window will display . In it you can give a key name or select the second radio button which tell you that the style will apply to all Toggle button . So , select that and then in the below You will see a radio button in the name of Resource Dictionary . There is drop down button from there select a generic.xaml file . Then Click Ok . See the Pic – 16.

Pic-16

33. Now we come in the design mode of the Toggle Button .  Let’s do it . here you will just need to add one Path. First take a rectangle and then choose pen .  Press “P”  in Your Key Board  Your pen will be selected. Then in the rectangle with the help of pen draw a triangle as like below pic – 17 .  Make the Color Red  of it . See pic – 17. If you can’t able to make a Path don’t worry , in beginning hand it is natural. Download Source Code and full copy the Style of the Toggle button from generic .xaml.  See in it You will get the Path also .

34. Now come in Animation. Interesting ?  First You need to go in the edit mode of the Panel
Pic-17

Then go to state tab . If you don’t able to find the state then do as like pic – 9 . If you get this then go forward. First one thing you need to do just go to the Properties tab and then find out the Transform catagory . There Click on the Rotate  symbol as  marked with red arrow in Pic – 18 . Now time to go in state again. You have already selected the Flip Button under Edit mode of Panel. Now in the State You will first find Two States . One Normal and another is Flipped. This two is not sufficient. We need to add two more . How ?, nice. Follow the next step.

Pic-18

35.  See the Pic – 19 below. In the States Normal click on the red mark. You will see one transaction

Pic-19

State to another states (Normal -> Flipped) Click on that . Your new state is ready. Follow the next Pic – 20  When you select Normal -> Flipped Transaction state then recording will going on and this will be realized with a red color. You can stop recording in the Edit time .  At the same time you will see that timeline editor . You can also add any number of key frame in here .  At a first glance you can see a yellow line on the Zero – Second marker. This yellow line represent the current location of time within a given storyboard. If you look carefully you able to see that directly above the yellow line an icon looks like a gray egg button with a plus sign to its right . See the Pic – 20.  I  have marked it with a red circle color . Actually this is Record key frame button . When you will click on it adds new key frame to current to current time location .

Pic-20

36.  When you will drag your yellow line as I show in the above pic – 20 . Look at the transaction time is 0.7s in the above Pic. Now when your Yellow line reaches in the 0.7 second timeline then make rotate angle 180 degree. See Pic- 18 above .  Be Sure that before drag the yellow line or anything you have selected the Fliped button in the above pic – 20 I have marked it * mark.  Now Click the Play button , you will able to see the button is rotating

37. Now to do similarly for Flipped to Normal state you need to follow step 34. Do same in this case drag the yellow line for 0.5 s. But here little different. What is that ?  ok, First see when your yellow line in zero –second then click the record Key frame button (the circle mark in Pic – 20 in 1st step which  is gray egg button) and then make the rotating 180 degree as same in pic – 18. Then drag the yellow line in 0.5 sec and then make the rotating 0 degree. Now click to play then you will see the button is rotating anti- clock wise.

38. ok one big step we have make successfully . Now other . What is that ? That is make to moving the front Border to back border . So , first select the front Border in your blend -> go states -> go normal to Flipped -> in the Time line when the yellow line in the zero sec then make in the Projection category Y angle (see pic 21) to 0 degree and then drag the yellow line in the 0.7 sec as you do same in the case of Flip Button . Make the Y angle 180 degree.  Now in this state (Normal to Flipped ) select the Back Border make Y angle – 90 when yellow line is in Zero sec as well as also in 0.7 sec .

Pic-21

39. Ok, Do now for another transaction state . From Flipped to Normal . Now here  Select the Front Border change the Y angle  to  90 degree when the yellow line in zero second  and make it 0 degree when the yellow line in the 0.5 sec. Next select the Back Border make Y angle 90 degree when yellow line zero sec and make it 0 degree when the yellow line in 0.5 sec . Now go to the both transactional state (Normal to Flipped and Flipped to normal ) see your border is moving from front side to back side . If you can’t able to do this complex thing just type the code in appropriate place. See the code .

<VisualTransition From="Normal" GeneratedDuration="0:0:0.7" To="Flipped">

<Storyboard>

<DoubleAnimation Duration="0:0:0.7" To="-90"

Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)"

Storyboard.TargetName="BackBorder"/>

<DoubleAnimation Duration="0:0:0.7" From="0" To="181"

Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)"

Storyboard.TargetName="FontBorder"/>

</Storyboard>

</VisualTransition>

<VisualTransition From="Flipped" GeneratedDuration="0:0:0.5" To="Normal">

<Storyboard>

<DoubleAnimation Duration="0:0:0.5" To="0"

Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)"

Storyboard.TargetName="FontBorder"/>

<DoubleAnimation Duration="0:0:0.5" To="0" Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)"

Storyboard.TargetName="BackBorder" From="90"/>

</Storyboard>

</VisualTransition>

40. Now Everything is complete . Just finishing last moment .  Add a simple line of code in generic .xaml page under border (both Front border and Back border ) that is <ContentPresenter/> . This is a class which will show the value of the Content Property of the control using Template Binding . If you don’t write this for both FontBorder as well also Back Border then , in xaml in your control no element can be added. So write it in both border.  See the code:

<ContentPresenter Content="{TemplateBinding FrontContent}"/> 

41. It is the time to go in Visual Studio Our Custom Control Class.  Write a private method in the name of ChangeVisualState() . This method is responsible for to choose a correct state as per request with Filp Button.  The method should be call in the OnApplyTemplate() method. Here is the Code :

private void ChangeVisualState(bool UseTransaction)

{

if (!this.IsFlipped)

{

VisualStateManager.GoToState(this, "Normal", UseTransaction);

}

else

{

VisualStateManager.GoToState(this, "Flipped", UseTransaction);

}

}

42. In OnApplyTemplate() method we need to set an event handler of Filp button. But  before that you need to find out your Filpbutton using specific name . For that you have to call the GetTemplateChild() method which is inherited from Framework Element along with the OnApplyTemplate() method. In this OnApplyTemplate() if can also add code for the missing element . If the element present then the  event  handler will call . At the end the ChangeVisualState() will call . Look at the code :

ToggleButton flipbutton = base.GetTemplateChild("FlipButton") as ToggleButton;

flipbutton.Click += new RoutedEventHandler(flipbutton_Click);

ChangeVisualState(false);

43. In Xaml page we use our CustomControl and within it we use some element in Front Border as well in back border . We Use AllowDrop = “true ” in Front Border because of we can drop our photo in the particular area. In The back border we use InkPresenter class which allow you to put your signature in there. These simple not very taugh. In the Code Behind of our Xaml page we also add some  Mouse event to draw with black color  for signature .Here we stop our journey .Download the Source Code and see the application run it . Drop your image and click red flip button . see how the border rotate and also you can see your signature as I did in Pic – 1 and pic- 2. Hope u enjoy . Bye ....

Page copy protected against web site content infringement by Copyscape

About the Author

debal_saha-9451
Full Name: DEBAL SAHA
Member Level: Starter
Member Status: Member
Member Since: 3/15/2011 4:01:43 AM
Country: India

http://silverlightpractice.blogspot.com/

Login to vote for this post.

Comments or Responses

Posted by: SheoNarayan on: 8/22/2011 | Points: 25
Great article Debal, keep it up!

Regards
Posted by: Vishvvas on: 8/25/2011 | Points: 25
Informative article and appreciable efforts. There needs to be corrections where the usercontrol and customcontrol are compared. A usercontrol can be build into dll, it can be part of Toolbox and also a customecontrol need not be a single control. Also in VS 2010 all WPF or silverlight who inherits from FrameworkElement are automatically added to toolbox. Custom controls, usercontrols all are resuable rather all controls...are meant for reusability. The article could be more readable if it is split into two parts.
Great efforts!

Login to post response

Comment using Facebook(Author doesn't get notification)