开发者

How do I make WPF TextBox acted as a compact form?

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


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜