This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on http://www.jameschambers.com/.

Wednesday, May 13, 2009

Adding a Hint to a Search Textbox in WPF

Are you running Vista?  Good.  Press the start key (or click on the Vista orb).  See how it says, “Start Search”?

It’s a nice effect: it’s contextual, it gives the user direction and it disappears the instant you start typing something.

If you want to give your users a similar experience with minimal effort, here’s how you add a hint (or help text) to a textbox or similar control in WPF.  I am added the hint to a combobox, so adjust your code as needed.

The approach we’re going to take here is similar to using a reflection surface in WPF, in that we’ll use a VisualBrush.  A couple of quick things: first, we set Stretch and TileMode to None (it would look a little weird, if not); second, we apply a slight transform to pad out the text (otherwise it hugs the border).

<VisualBrush x:Key="SearchHint" TileMode="None" Stretch="None" AlignmentX="Left">
<
VisualBrush.Transform>
<
TranslateTransform X="5" Y="0" />
</
VisualBrush.Transform>
<
VisualBrush.Visual>
<
Grid>
<
TextBlock FontStyle="Italic"
Foreground="Black"
Opacity="0.3"
Text="Enter search text…"/>
</
Grid>
</
VisualBrush.Visual>
</
VisualBrush>



You’ll need to add this visual brush to the window or control resources, or put it in a resource file.



Next, we want to use a trigger so that the background is changed from it’s default when the string is empty to be the SearchHint instead.  WPF takes care of changing it back for us when there is text in the box.



I have this as code in my ComboBox tag:




<ComboBox.Style>
<
Style TargetType="ComboBox">
<
Style.Triggers>
<Trigger Property="Text" Value="">
<
Setter Property="Background" Value="{StaticResource SearchHint}"/>
</
Trigger>
</Style.Triggers>
</
Style>
</
ComboBox.Style>




There you have it.  You may want to add multiple brushes, or even an image or anything (I used a grid for this purpose in the Visual, but you can set this to any single element you like).  If you’re presenting data or there is a chance you could get a null in there you may wish to handle that Trigger condition as well.



Man, alive…I really need to do something about this blog template so my code doesn’t look like arse.



edit: Here is the original article I based my work off of. 

3 comments:

  1. Absolutely awsome. Thank you.

    ReplyDelete
  2. Perfect ... thanks for the post .

    ReplyDelete
  3. This was extremely helpful, thanks!!!

    ReplyDelete