views:

22

answers:

2

How do I make WPF TextBox acted as a compact form?
This means that "label text" inside TextBox is hiding on the click or when there is "real text".
See working prototype

A: 

You can use a data trigger in the style for the TextBox, and set the background to something that includes your text. A sample that works simply would be this:

<TextBox>
  <TextBox.Style>
    <Style TargetType="{x:Type TextBox}">
      <Style.Triggers>
        <DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}}" Value="">
          <Setter Property="Background">
            <Setter.Value>
              <VisualBrush Stretch="None" AlignmentX="Left">
                <VisualBrush.Visual>
                  <TextBlock Text="This is the label text" Foreground="Silver" />
                </VisualBrush.Visual>
              </VisualBrush>
            </Setter.Value>
          </Setter>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </TextBox.Style>
</TextBox>

Tested in Kaxaml; the "label text" alignment isn't quite right, and you'd maybe want to refactor this into something more reusable for production code.

EDIT: to cover the "Hide on focus" scenario you'd need a more complicated trigger. Replace the datatrigger with this:

        <MultiDataTrigger>
          <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding Text, RelativeSource={RelativeSource Self}}" Value="" />
            <Condition Binding="{Binding IsKeyboardFocused, RelativeSource={RelativeSource Self}}" Value="False" />
          </MultiDataTrigger.Conditions>
          <Setter Property="Background">
            <Setter.Value>
              <VisualBrush Stretch="None" AlignmentX="Left">
                <VisualBrush.Visual>
                  <TextBlock Text="This is the label text" Foreground="Silver" />
                </VisualBrush.Visual>
              </VisualBrush>
            </Setter.Value>
          </Setter>
        </MultiDataTrigger>
Dan Puzey
Just realised I didn't cover the "hide on focus" behaviour... Will update if I get chance.
Dan Puzey
A: 

just have a look at this link

http://stackoverflow.com/questions/833943/watermark-textbox-in-wpf

Kishore Kumar