WPF: Adding text as a background of TextBox or ComboBox

One of those small things I liked in Vista is help text in the background of various text boxes, such as Search in Explorer:

1

When you click on it, the text disappears, leave it without typing anything, you again see the text. In many places this might be a useful thing - it helps user to determine what should be written inside and there is no additional place needed to put the label. So I wanted to figure out how to do this in pure XAML without any additional code. It turned out this was pretty simple.

There was a sample in MSDN describing how to do this using background image and code-behind. But I didn't want separate image nor any code written. So instead of using image, I took VisualBrush for background and triggers to hide/display it. Now it looks like:

2

And the code:

<ComboBox IsTextSearchEnabled="True" StaysOpenOnEdit="True" 
          Width="150" Height="24"  IsReadOnly="False" IsEditable="True">
  <ComboBox.Resources>
    <VisualBrush x:Key="HelpBrush" TileMode="None" Opacity="0.4" Stretch="None" AlignmentX="Left">
      <VisualBrush.Visual>
        <TextBlock FontStyle="Italic" Text="Type or select from list"/>
      </VisualBrush.Visual>
    </VisualBrush>
  </ComboBox.Resources>
  <ComboBox.Style>
    <Style TargetType="ComboBox">
      <Style.Triggers>
        <Trigger Property="Text" Value="{x:Null}">
          <Setter Property="Background" Value="{StaticResource HelpBrush}"/>
        </Trigger>
        <Trigger Property="Text" Value="">
          <Setter Property="Background" Value="{StaticResource HelpBrush}"/>
        </Trigger>
      </Style.Triggers>
    </Style>
  </ComboBox.Style>
  <ComboBoxItem>First item</ComboBoxItem>
  <ComboBoxItem>Another item</ComboBoxItem>
</ComboBox>

 

Technorati Tags: ,

posted @ Wednesday, April 23, 2008 11:43 AM

Print

Comments on this entry:

# re: WPF: Adding text as a background of TextBox or ComboBox

Left by James at 5/8/2008 8:44 AM
Gravatar
Thanks! Was looking for this

# re: WPF: Adding text as a background of TextBox or ComboBox

Left by Boodaleh at 5/22/2008 11:18 PM
Gravatar
I presume this only works in ASP.NET, not classic...

# re: WPF: Adding text as a background of TextBox or ComboBox

Left by Philip Patrick at 5/25/2008 2:05 PM
Gravatar
Well, it is not for ASP.NET, but for Windows Applications. WPF is something that is supposed to replace Windows Forms in .NET.

# re: WPF: Adding text as a background of TextBox or ComboBox

Left by MIchel Renaud at 10/19/2008 3:57 PM
Gravatar
Thanks! This is exactly what I was looking for (and I was really complicating my life trying to do it - this is a clean and simple approach!)

Your comment:



 (will not be displayed)


 
 
 
Please add 8 and 2 and type the answer here:
 

Live Comment Preview: