ObjectSharp Blogs

You are currently viewing

Bruce Johnson's SOA(P) Box

Using SOA in the .NET world


Setting the Default Style for a Custom Silverlight Control

Like so many of my posts, this one is as much about keeping a log of what I learned. And, in this particular case, since I had a difficult time finding the answer (and the answer is relatively new), a blog posts is doubly worthwhile.

I was trying to write a custom control for Silverlight 3. It was an extension to a ListBox, so I created a class that derived from ListBox and added my neat-o cool functionality. However, part of the requirements for the control was (for example) that it needed to be horizontal and that the scroll bars needed to be hidden. For this, the best approach is to define a default template for the control.

The default template is basically the style that is applied to the control in the absence of designer requests to the contrary. Practically, it is exactly the same as any other style that you would create. What makes it different is that the user of the custom component does not need to do anything to have the style applied.

In order to accomplish this feat requires three steps. The first has been true since Silverlight 2, that being that the style needs to be placed into a file named Generic.xaml. In the past it was sufficient to place the style in said file and set the TargetType of the style to be the custom control. However at Silverlight 3, two additional requirements were added. The first is that the Generic.xaml needs to be placed into a directory called Themes. The second is that the following line of code needs to the constructor for the custom control.

this.DefaultStyleKey = typeof(customcontrolname);

Once these conditions have been met, the default style will get picked up. It was the last two steps that stymied me, as many of the existing posts talk about one, but not both of the requirements.

As a convenience, there is now a TemplatedSilverlightControl template that actually sets up the necessary files, directory and code to make all of this work without further thought. And I like not having to think (other than remembering to use the correct template, that is).

Comments

    No Comments

Leave a Comment

(required) 
(optional)
(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS