我如何添加一个提示文字,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
,并在风格
:
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>
要增加可重用性这个风格
,也可以创建一组附加属性来控制实际的提示标语文本,颜色,方位等。
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.