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

How to access Control Template parts from Code Behind

| Wednesday, May 18, 2011
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 are 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. I appreciate your feedback as always.

Background

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:

How to create a Custom Control in Silverlight?
How to design a Custom Control by editing the Part Template?
How to implement Template Binding in Silverlight Custom Control?
Once you are familiar with the previous code, let's 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 metadata 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 required. If you need them 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:

Read more: Codeproject

Posted via email from Jasper-net

0 comments: