So you've done it, you created a brand new empty project, and now your ready to try some things out in SL2. You add a few random controls, it could be an Image control, or maybe a few TextBox controls.
After 10-15 minutes you've probably got the basics working, and now you're ready to do something more advanced, like lets say create a Custom Control (CustomControl tag) and place it on the default main page (Page.xaml).
Creating a UserControl
To start you are going to do what your used to, you will right-click on the project, you'll select add, then New Item.
In the next screen you'll add a Silverlight User Control and name it whatever you want.
As a final step you'll add some text (or some other controls) to add a visual element to your new custom control, and move back to Page.xaml to start using it.
Problem... where is my control?
And so the frustration will begin (unless your smarter then me). You will not find any way to reference your newly created control, oh the pain.
Sure, MSDN has a reference on this subject, and there is even mention of a custom control in the excellent ScottGu Digg Sample, but if you are anything like me, you are still lost.
Solution
The solution is actually ever simple once you "Get it", so here is a simple explanation:
You need to add your own projects namespace to your Page.xaml file before you can use UserControls from your own project and start using them.
In my case the custom control was named PopupSection (hence PopupSectoin.xaml in the screenshot above), but I could not get my code to use it until I did this:
As you can see on the 4th line in the screenshot above I implement a reference to my namespace by using xmlns tag reference, that configures uc (it can be named anything you want, I just like the name uc) to reference the namespace of my project, that happens to be SilverlightInterfaceDemo (same as the name under x:class="...)
So now like magic intellisense has my control listed when I type in the following code anywhere inside of the Page.xaml XAML:
(In the code above I reference my new control using the uc:PopUpSectoin name, and can then start setting properties on it like the Name property shown above.)
Bad Assumptions
What I still don't "get" is why Page.XAML does not automatically contain reference to "UserControls" inside of the project. My understanding of the full SL2 architecture is still growing so more on this later.
Conclusion
Silverlight 2 is an amazing technology once you get beyond the learning curve of the basics and I hope this post helps at least one person in the future to start using User Controls. As always if anything in this post is wrong or can be done easier, don't hesitate to contact me or post a comment.
- Additional Learning: Hands-on labs that cover UserControls and Blend 2.5


0 comments:
Post a Comment