This is a mirror of official site: http://jasper-net.blogspot.com/

How to access Control Template parts from Code Behind?

| Sunday, April 10, 2011
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.
 
image%5B3%5D.png?imgmax=800
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:
 
image%5B7%5D.png

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:

image%5B16%5D.png?imgmax=800

Read more: Kunal's Blog

Posted via email from Jasper-net

0 comments: