设为“默认"使用 XAML 显示在没有焦点的空 TextBox 中的文本 [英] Make "default" text to appear in an empty TextBox without focus using XAML
问题描述
我想创建一个文本框,如果是的话,里面会出现一个灰色的默认"文本
I want to create a TextBox, which would have a gray "default" text appear in it, if it's
a) 空
b) 失去焦点
当用户输入文本框时,灰色的默认"文本应该会消失.
when the user enters the text box, the gray "default" text should dissappear.
我已尝试使用 ControlTemplate.Triggers
执行此操作,但似乎找不到 HasFocus
属性.
I've tried to do this using ControlTemplate.Triggers
, but I can't seem to find HasFocus
property.
使用 XAML 执行此操作的最佳方法是什么?
What is the best way to do this using XAML?
推荐答案
虽然重新发明轮子没有真正的好处,但看看如何做到这一点可能会很有趣.执行此操作的最简单方法(在纯 XAML 中)是为 TextBox
创建一个 ControlTemplate
,当它未聚焦时覆盖一个 TextBlock
不包含文本:
Whilst there is no real benefit in re-inventing the wheel, it might be interesting to see how this can be done. The easiest way to do this (in pure XAML) is to create a ControlTemplate
for the TextBox
that overlays a TextBlock
when it is not focussed and does not contain text:
<ControlTemplate TargetType="TextBox">
<Grid>
<TextBox Text="{Binding Text, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="Your Prompt Here"
Margin="5,0,5,0"
Foreground="#FF808080"
FontStyle="Italic"
IsHitTestVisible="False"
x:Name="UserMessage"
Visibility="Hidden"/>
</Grid>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="Text" Value=""/>
<Condition Property="IsKeyboardFocusWithin" Value="False"/>
</MultiTrigger.Conditions>
<Setter Property="Visibility" TargetName="UserMessage" Value="Visible"/>
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
MultiTrigger
表示如果 Text
属性为空且 TextBox 没有键盘焦点,则将 Visibility 设置为 Visible"
The MultiTrigger
means "set Visibility to Visible if the Text
property is empty AND the TextBox does not have keyboard focus"
如果你想让它更可重用,那么你可以使用它作为默认模板和包含提示消息的依赖属性创建一个自定义控件
If you want to make this more reusable then you could create a custom control with this as it's default template and with a Dependency Property containing the prompt message
这篇关于设为“默认"使用 XAML 显示在没有焦点的空 TextBox 中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!