Thursday, April 07, 2011

How to implement Template Binding in Silverlight Custom Control?

Continuing to our 2nd chapter of the series here on Silverlight Custom Control. In this chapter we will discuss on dynamically setting the Content and other properties to our Custom Control that we implemented earlier. After reading this article, you will be able to create properties and set content dynamically to your control.
So, lets start describing them and learn something again today. These series of posts are mainly targeted for beginners but anyone can read it to refresh their learning. Don't forget to leave your comment at the end of the post. Any queries, please drop a line. I will try to help you as early as I can.
 Background
I hope, you read my previous posts. Those will help you to understand this one very easily. If you didn't read them or want to brush up before starting this chapter, find them here:
How to create a Custom Control in Silverlight?
How to design a Custom Control by editing the Part Template?
Once you are familiar with the previous context, lets start with this one. We will use the same example here which will give you more visualization on the sample code.
Working with the Template Part
Template parts are defined in the XAML inside the style. In our example, we have three part called "PART_HeaderPanel", "PART_HeaderText" and "PART_Content". Those are already declared in the style and you can find them here:

image3.png?imgmax=800

 Now it's time to initialize them in the code. You can escape this step but it is recommended that you should do this before working with those parts. In this article, we don't need them directly but we are doing this steps here itself. We will talk more on this in next chapter.
We will declare and initialize the template part by setting the TemplatePart attribute to the class. You need to do this for all the template part. Again this step is not mandatory but recommended. This also ensures that, your user of this custom control should know what are the template parts that you used in your style. This information you will find in the meta class if you declare it here.
See the below sample code snippet to know how to declare the Template Part:

image7.png?imgmax=800

Read more: Kunal's Blog