Saturday, June 23, 2007

How to build a Silverlight control?

Very recent I build a web top in Silverlight. As this is a new technology I have to build lot of control for myself. And I find some difficulty to building control. As I have very short memory I write my findings in my blog so that they will be accessible from anywhere…

I build my project with Orcas so that the entire feature I am writing related to Orcas. Right Button click to your Silverlight project and click add New Item; from Silverlight project choose Silverlight User Control. Give a name to your control, let Button so you will get two file

  1. Button.xaml
  2. Button.xaml.cs

Button.xaml is used to render your graphics and Button.xaml.cs is used as code behind file. By default it will gives you a canvas and you can draw your necessary items. Add your necessary items to render the button. Let I add two more canvas inside it. And I give them name OuterCanvas and InnerCanvas.

In default page given with Silverlight project you can find any Control by

this.FindControl(“ControlName”);

But in case of control you cannot find any control by

this.FindControl(“ControlName”);

You have to write two lines in your control’s constructor.

Stream ioStream = typeof(Button).Assembly.GetManifestResourceStream("Button.xaml");

FrameworkElement fe= this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd());

And now you have to write

fe.FindControl(“ControlName”);

Now you can subscribe any event, and what ever you want.

Again you can add other rendering item by code. This is very simple and you don’t have to write any xaml for this.

TextBlock block = new TextBlock();

block.SetProperty<double>(Canvas.LeftProperty,5);

block.SetProperty<double>(Canvas.TopProperty,5);

Canvas innerCanvas = fe.FindControl(“innerCanvas”) as Canvas;

innerCanvas.Children.Add(block);

This is as simple as it is…

Cautions:

1. Don't try to subscribe GetFocus() this is restricted only for root element.

2. Don't make canvas full screen in any event it can be done only in MouseUpEvent and MouseDownEvent.

So, lets have fun with Silverlight.

Feel free to contact me for any convenience.

No comments:

Post a Comment

Please, no abusive word, no spam.