如何向 WPF 文本框添加提示文本? [英] How can I add a hint text to WPF textbox?

查看:34
本文介绍了如何向 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??

推荐答案

您可以使用 VisualBrushStyle 中的一些触发器更轻松地完成此操作:

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.

这篇关于如何向 WPF 文本框添加提示文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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