Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

Channels ▼


Handling Events Within Silverlight Control Templates

Dan Wahlin (Microsoft Most Valuable Professional for ASP.NET and XML Web Services) is the founder of The Wahlin Group (www.TheWahlinGroup.com) which provides .NET, SharePoint, and Silverlight consulting and training services. Dan blogs at http://weblogs.asp.net/dwahlin.

One of the great features Silverlight offers is the ability to customize controls by using control templates. If you don't like how a particular control looks you can modify the template and in many cases be ready to use the new control without writing a single line of C# or VB code. I'm working on a client application that uses the AutoCompleteBox found in the Silverlight Toolkit and needed a way to change it from a regular TextBox to more of an editable ComboBox. Fortunately the Silverlight Toolkit samples (for Silverlight 2 and 3) already do something like this as you can see in Figure 1. (Once on the page click on AutoCompleteBox to the left and then on the Styling tab at the top of the page to see the sample).

Figure 1

The sample modifies the standard AutoCompleteBox to look more like an editable ComboBox by defining a custom control template with a ToggleButton in it (Tim Heuer provides a nice walk through of this type of customization here if you're interested). Listing One is a simplified version of the Silverlight Toolkit's sample template that I'm using:

<ControlTemplate TargetType="input:AutoCompleteBox">
    <Grid Margin="{TemplateBinding Padding}">
        <TextBox IsTabStop="True" x:Name="Text" 
          Style="{TemplateBinding TextBoxStyle}" Margin="0" />
        <ToggleButton x:Name="ToggleButton"
            Style="{StaticResource ComboToggleButton}"
            Background="{TemplateBinding Background}" 
            Height="16" Width="16"
                <Path x:Name="BtnArrow" Height="4" Width="8" Stretch="Uniform" 
                  Data="F1 M 301.14,-189.041L 311.57,-189.041L 
                  306.355,-182.942L 301.14,-189.041 Z " 
                      Margin="0,0,6,0" HorizontalAlignment="Right">
                        <SolidColorBrush x:Name="BtnArrowColor" Color="#FF333333"/>
        <Popup x:Name="Popup">
            <Border x:Name="PopupBorder" HorizontalAlignment="Stretch" Opacity="1.0" 
                    <TranslateTransform X="2" Y="2" />
                    <SolidColorBrush Color="#11000000" />
                        <ListBox x:Name="Selector" 
                             ItemTemplate="{TemplateBinding ItemTemplate}" />

Listing One

Looking at the template you'll see that it defines a ToggleButton with a Click event and associated event handler named DropDownToggle_Click. Listing Two is what the ToggleButton's Click event handler looks like:

private void DropDownToggle_Click(object sender, RoutedEventArgs e)
    FrameworkElement fe = sender as FrameworkElement;
    AutoCompleteBox acb = null;
    while (fe != null && acb == null)
        fe = VisualTreeHelper.GetParent(fe) as FrameworkElement;
        acb = fe as AutoCompleteBox;
    if (acb != null)
        if (String.IsNullOrEmpty(acb.SearchText))
            acb.Text = String.Empty;
        acb.IsDropDownOpen = !acb.IsDropDownOpen;

Listing Two

You can see that the code uses the VisualTreeHelper class to access the parent of the ToggleButton which is the AutoCompleteBox. Once the AutoCompleteBox parent is found the code handles showing or hiding the Popup control that's part of the control template by setting the IsDropDownOpen property to True or False.

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.