How to access Control Template parts from Code Behind?

Here is the last chapter of the series for Silverlight Custom Control. In this article, we will learn how to access the template parts from code behind to do various operations in the UI front.


Hope, you read the previous three articles and familiar with the Custom control as of now. This article will help you to understand accessibility of the template parts from the code. So, let's start discussing now. Appreciate your feedback as always.





I hope, you read my previous three articles. Those will help you to understand the context of this one very easily. If you didn't read them or want to brush up before starting this chapter, find them here:

  1. How to create a Custom Control in Silverlight?
  2. How to design a Custom Control by editing the Part Template?
  3. How to implement Template Binding in Silverlight Custom Control?

Once you are familiar with the previous code, lets start with this one. We will use the same example here which will give you better visualization on the sample code.




Brush up Previous Chapter on Parts

In our previous article, we discussed about template parts. These are the UI elements available in your style of the custom control. Generally, we prefix their name with "PART_". In the control's class, we initialize them with the attribute called "TemplatePart" as shown below. This is to make sure that, the meta data of the class shows them properly and your user can easily understand which UI elements you used there. Also, this is beneficial for you to easily access the parts in the file.




Once you marked the template parts in the class, you can declare the member variables to store the instance of those parts, so that, you can access them easily. Remember that, only get the instance whenever require. If you need them in multiple times, better declare them as member variable and use throughout the life of the control.




Declaring Private members for Part instance

We need to declare the member variables now to store the instance of the template parts. In this example, we used three parts called "Border", "TextBlock" and "ContentPresenter". Declare the private instances of them. This is simple enough. The below screenshot will help you to understand:




Always make sure that, you are declaring them as Private member. Never declare as Public because, it will make your control vulnerable. Declaring as public will give your user direct access to the template part and thus your control will never be secure.




Getting Template Part instance

It's time for us to get the instance of the part, so that, we can do whatever we need with them. Try to get the instance locally whenever require but if you are accessing them from multiple place inside your control, it is recommended to load them at the beginning or at the time of first access.


To make you familiar with it, we will use it at the first load. Before describing more, I want to tell you one thing: "Don't get the instance in the constructor. In constructor, you may get them as null if they are not already loaded in memory."


So what to do? There is overridable method named "OnApplyTemplate()". This is part of the base class "Control". You can get the instance of the parts there. This method gets call automatically when you apply a template to your custom control. So, whenever the template applied, you have to refresh the instances.


Here is the implementation of the same:





Inside the OnApplyTemplate() method, you can call GetTemplateChild(...) method to get the instance of the template part.




You have to specify the name of the template part i.e. child name there. The method will search for the named template part and fetches the instance of the same.




For our example, we will get all the three template child instance and will store them in the declared member variables to use them later.


Here is the actual code snippet, for your reference:




It is always recommended to check whether the retrieved instance of the template part is available or null, before doing any operation. Because, it may change or remove in future from XAML mistakenly. Hence, just check for null instance and throw a NullReferenceException to the user.


Get the full source code here:


public override void OnApplyTemplate()
    // Code to get the Template parts as instance member
    part_headerPanel = GetTemplateChild("PART_HeaderPanel") as Border;
    part_headerText = GetTemplateChild("PART_HeaderText") as TextBlock;
    part_content = GetTemplateChild("PART_Content") as ContentPresenter;
    if (part_headerPanel == null || part_headerText == null || part_content == null)
        throw new NullReferenceException("Template parts not available");


This null check is require only once if you place them in the OnApplyTemplate() method. Now you will be able to use them in the code whenever you require them. I am not going to discuss that here.




What Next?

It's the time again to tell you "What's Next?". Hope all the chapters of the series helped you a lot to understand the Custom Control. Once we are done with our demonstration, you will be able to create your custom controls very easily. Do let me know, if you need more information on the same or want some help.


Don't forget to provide your feedback at the end of the page. This will help me to energies more to serve you better in future with more detailed articles.


I am going to post the next and last part of the series soon, where we will discuss on External Custom Library and how to use them in your project. Till then, read my other articles and give your feedback. Happy Coding.

If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter, Facebook, Google+ and LinkedIn. I would love to hear your thoughts and opinions on my articles directly.

Don't forget to share your feedback/queries in the comment section below.


  1. This is a very nice explanation by u. I have always query on why the OnApplyTemplate() used ,
    What is it necessary?...... This make one nice explanation .

    One thing to ask , Is it Possible to make a custom control & add it to Tool Box , So that any time i can drag & drop it in My View Design page ...If it Possible , then it will be very Interesting , If U have any example pl publish it in ur blog.

    Keep Continue Writing. I like ur blog ..because it is simple & make sense.

  2. I will post the same tomorrow. I forgot to mention that in the previous chapters. I will do a post about it. Thanks.

  3. Nice Work. but images didn't load.

  4. Not sure, looks good here. Try refreshing the browser again.

  5. Can you please write article on how to create and handle custom events on custom controls.

    Thank you in advance !

  6. Can you please write article on how to create and handle custom events on custom controls.

    Thank you in advance !

  7. This is really very useful series of article for beginers

  8. Again, very clear tutorial. Thank you!
    But could you please give us some example of use for the private members part_headerPanel, part_HeaderText and part_Content?
    At the beginning of this tutorial, you wrote something about doing some UI operations. But as a Silverlight beginner, I just don't know what to do with these members...

  9. Thank you very much. Seldom I found such a clear structured tutorial. Also now my fear from custom controls has gone.

  10. Thanks for the feedback. Glad to hear that, your fear has gone away. :)

  11. Great article. The only one on the internets that can explain to a silverlight novice how to access the contents of a ControlTemplate .

  12. Great article, really very useful, very clear and simple language :)


  13. Excellent Job. Very clear and well done

  14. Well done!
    This helped me out after a day of trial and error...
    Thanks, man!


  15. Great article !
    Very helpful series for the beginners. It has clear dark clouds around the custom control development for me.
    I want to use text block and text box in conjunction. So, that when user click on text block, it does convert to text box to allow editing the text in place. Should I use Custom control or User control?

    1. Hi Kapil,

      This depends on your control's design and functionality. But in your case, you should go for Custom Control, if it is just replacing a TextBlock to a TextBox and if you want to use that in multiple places.

  16. Hello Kunal,

    Great posts! I'm just missing one thing. I'd like to know how do I apply visual validation to my custom control, like that red border with a Tooltip that we can see in TextBox. I realized that TextBox works with VisualState, but I didn't understand yet if I need to write some code in the code behind of my custom control.


© 2008-2018 Kunal-Chowdhury.com | Designed by Kunal Chowdhury
Back to top