Highlighting AutoCompleteBox improvements thanks to Silverlight 3

24 March 2009

About half a year ago, I blogged a nice "highlighting AutoCompleteBox" post that allowed you to use the Silverlight Toolkit's AutoCompleteBox control to give your users an experience just like that of Internet Explorer 8, Firefox, and other nice interfaces. Now, with Silverlight 3, the sample app has dropped in size, removing the need for 160 lines of "hack" code to enable the scenario. This functionality was done using a helper control that I built, called HighlightingTextBlock, that has two primary dependency properties: the Text to display, and the HighlightText (subset) that should be highlighted visually.
If you have the Silverlight 3 Beta developer runtime, click here to view the sample app. In Silverlight 2, without UI-to-UI binding (no ElementName), unfortunately this blog post included a little intense code to actually walk the visual tree, find all the HighlightingTextBlock instances, and update their values, whenever the searching changes. This was because a direct binding could not be made to the parent AutoCompleteBox control's "SearchText" property, which is a string value that is set to whatever the current searching text is. Thanks to the Silverlight 3 Beta's great support for ElementName binding, I was able to update the sample to be super easy. Using this, I can use the following ItemTemplate setting for any AutoCompleteBox to enable this very nice highlighting behavior.

<input:AutoCompleteBox

    x:Name="HighlightingAutoCompleteBox" IsTextCompletionEnabled="False" SearchMode="Contains">

    <input:AutoCompleteBox.ItemTemplate>

        <DataTemplate>

            <highlightingTextBlock:HighlightingTextBlock

                HighlightText="{Binding SearchText, ElementName=HighlightingAutoCompleteBox}"

                Text="{Binding}"

                HighlightBrush="#FF44A0FF" />

        </DataTemplate>

    </input:AutoCompleteBox.ItemTemplate>

</input:AutoCompleteBox>

I think this would work with Relative Source as well, but haven't spent the time to try yet. Hope this helps! I can't wait for the final release of Silverlight 3, this beta is a really nice set of improvements.

Jeff Wilcox is a Software Engineer at Microsoft in the Open Source Programs Office (OSPO), helping Microsoft engineers use, contribute to and release open source at scale.

comments powered by Disqus