如何向 WPF 文本框添加提示文本?
问题描述:
例如,当文本框为空时,Facebook 在搜索文本框中有一个搜索"提示文本.
For example, Facebook has a "Search" hint text in the Search text box when the textbox is empty.
如何使用 WPF 文本框实现此目的??
How to achieve this with WPF text boxes??
答
您可以使用 VisualBrush
和 Style
中的一些触发器更轻松地完成此操作:>
You can accomplish this much more easily with a VisualBrush
and some triggers in a Style
:
<TextBox>
<TextBox.Style>
<Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="Search" Foreground="LightGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="Background" Value="White" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
为了增加此Style
的可重用性,您还可以创建一组附加属性来控制实际提示横幅文本、颜色、方向等.
To increase the re-usability of this Style
, you can also create a set of attached properties to control the actual cue banner text, color, orientation etc.