如何向WPF文本框添加提示文本?

Lou*_*hys 99 .net wpf user-interface textbox

例如,当文本框为空时,Facebook在"搜索"文本框中有"搜索"提示文本.

如何用WPF文本框实现这一点?

Facebook的搜索文本框

sel*_*dog 155

您可以使用以下内容中的VisualBrush一些触发器更轻松地完成此操作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>
Run Code Online (Sandbox Code Playgroud)

为了增加此功能的可重用性Style,您还可以创建一组附加属性来控制实际的提示横幅文本,颜色,方向等.

  • 解决方案应该是Hint ="请输入你的文字"而不是20个元素......唉,传说中的内置文本框不支持这个... (19认同)
  • 虽然这种方法可能适用于默认条件,但当文本框已包含背景画笔或表单背景与文本框不同时,它不起作用. (8认同)
  • 如果有人想知道如何使用附加属性来增加样式可重用性,请参阅:http://stackoverflow.com/a/650620/724944 (4认同)

小智 52

这是我的简单解决方案,改编自Microsoft(https://code.msdn.microsoft.com/windowsapps/How-to-add-a-hint-text-to-ed66a3c6)

    <Grid Background="White" HorizontalAlignment="Right" VerticalAlignment="Top"  >
        <!-- overlay with hint text -->
        <TextBlock Margin="5,2" MinWidth="50" Text="Suche..." 
                   Foreground="LightSteelBlue" Visibility="{Binding ElementName=txtSearchBox, Path=Text.IsEmpty, Converter={StaticResource MyBoolToVisibilityConverter}}" />
        <!-- enter term here -->
        <TextBox MinWidth="50" Name="txtSearchBox" Background="Transparent" />
    </Grid>
Run Code Online (Sandbox Code Playgroud)

  • 如果将TextBlock设置为`IsHitTestVisible =“ False”,则此解决方案特别有效。 (2认同)

mxg*_*250 10

通过将文本颜色最初设置为灰色并添加事件处理程序来获取和丢失键盘焦点,从而在代码隐藏中执行此操作.

TextBox tb = new TextBox();
tb.Foreground = Brushes.Gray;
tb.Text = "Text";
tb.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_GotKeyboardFocus);
tb.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_LostKeyboardFocus);
Run Code Online (Sandbox Code Playgroud)

然后是事件处理程序:

private void tb_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    if(sender is TextBox)
    {
        //If nothing has been entered yet.
        if(((TextBox)sender).Foreground == Brushes.Gray)
        {
            ((TextBox)sender).Text = "";
            ((TextBox)sender).Foreground = Brushes.Black;
        }
    }
}


private void tb_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    //Make sure sender is the correct Control.
    if(sender is TextBox)
    {
        //If nothing was entered, reset default text.
        if(((TextBox)sender).Text.Trim().Equals(""))
        {
            ((TextBox)sender).Foreground = Brushes.Gray;
            ((TextBox)sender).Text = "Text";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • -1在后面的代码中执行它:使控件混乱,并且很可能会干扰其他控制逻辑,如果不是现在,那么将来. (6认同)

Mah*_*ili 6

使用materialDesign HintAssist怎么样?我正在使用它,您也可以添加浮动提示:

<TextBox Width="150" Height="40" Text="hello" materialDesign:HintAssist.Hint="address"  materialDesign:HintAssist.IsFloating="True"></TextBox>
Run Code Online (Sandbox Code Playgroud)

我用Nuget Package安装了Material Design,文档链接中有安装指南

  • 非常有用的库 (3认同)

Kis*_*mar 5

您必须通过继承文本框来创建自定义控件.下面的链接有一个关于搜索文本框示例的极好示例.请看看这个

http://davidowens.wordpress.com/2009/02/18/wpf-search-text-box/

  • 不鼓励仅提供链接的答案 (2认同)

Dav*_*son -13

对于WPF来说,没有办法。你必须模仿它。请参阅此示例。第二种(不稳定的解决方案)是托管一个继承自 TextBox 的 WinForms 用户控件,并将 EM_SETCUEBANNER 消息发送到编辑控件。IE。

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam);

private const Int32 ECM_FIRST = 0x1500;
private const Int32 EM_SETCUEBANNER = ECM_FIRST + 1;

private void SetCueText(IntPtr handle, string cueText) {
    SendMessage(handle, EM_SETCUEBANNER, IntPtr.Zero, Marshal.StringToBSTR(cueText));
}

public string CueText {
    get {
        return m_CueText;
    } 
    set {
        m_CueText = value;
        SetCueText(this.Handle, m_CueText);
}
Run Code Online (Sandbox Code Playgroud)

另外,如果您想托管 WinForm 控件方法,我有一个已经包含此实现的框架,称为 BitFlex Framework,您可以在此处免费下载

如果您想了解更多信息,请参阅有关 BitFlex 的文章。您将开始发现,如果您正在寻找 Windows 资源管理器样式的控件,那么它通常永远不会开箱即用,并且因为 WPF 通常不与句柄一起使用,所以您无法像您一样围绕 Win32 或现有控件编写简单的包装器与 WinForms。

截屏: 在此输入图像描述

  • 抱歉,这个答案根本不正确。而且所有链接都已损坏。 (3认同)