设为“默认”文本使用XAML出现在没有焦点的空TextBox中 [英] Make "default" text to appear in an empty TextBox without focus using XAML

查看:91
本文介绍了设为“默认”文本使用XAML出现在没有焦点的空TextBox中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个TextBox,如果它是灰色的默认文本,如果它是

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没有键盘焦点

The MultiTrigger means "set Visibility to Visible if the Text property is empty AND the TextBox does not have keyboard focus"

可重用,则可以使用此模板作为默认模板并使用包含提示消息的Dependency属性来创建自定义控件

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆