.net - 如何在WPF文本框中添加提示文本?

例如,Facebook有一个"搜索" 当文本框为空时,在“搜索”文本框中提示文本。

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

Facebook's search textbox

Louis Rhys asked 2019-08-13T05:18:07Z
13个解决方案
148 votes

您可以使用Style以及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的可重用性,您还可以创建一组附加属性来控制实际提示横幅文本,颜色,方向等。

sellmeadog answered 2019-08-13T05:18:27Z
46 votes

这是我的简单解决方案,改编自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>
Martin Schmidt answered 2019-08-13T05:18:52Z
10 votes

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

TextBox tb = new TextBox();
tb.Foreground = Brushes.Gray;
tb.Text = "Text";
tb.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_GotKeyboardFocus);
tb.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_LostKeyboardFocus);

然后是事件处理程序:

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";
        }
    }
}
mxgg250 answered 2019-08-13T05:19:23Z
5 votes

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

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

Kishore Kumar answered 2019-08-13T05:19:54Z
3 votes

你可以用一种非常简单的方式做。  我们的想法是将Label放在与文本框相同的位置。 如果文本框没有文字且没有焦点,则您的标签将可见。

 <Label Name="PalceHolder"  HorizontalAlignment="Left" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Height="40" VerticalAlignment="Top" Width="239" FontStyle="Italic"  Foreground="BurlyWood">PlaceHolder Text Here
  <Label.Style>
    <Style TargetType="{x:Type Label}">
      <Setter Property="Visibility" Value="Hidden"/>
      <Style.Triggers>
        <MultiDataTrigger>
          <MultiDataTrigger.Conditions>
            <Condition Binding ="{Binding ElementName=PalceHolder, Path=Text.Length}" Value="0"/>
            <Condition Binding ="{Binding ElementName=PalceHolder, Path=IsFocused}" Value="False"/>
          </MultiDataTrigger.Conditions>
          <Setter Property="Visibility" Value="Visible"/>
        </MultiDataTrigger>
      </Style.Triggers>
    </Style>
  </Label.Style>
</Label>
<TextBox  Background="Transparent" Name="TextBox1" HorizontalAlignment="Left" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Height="40"TextWrapping="Wrap" Text="{Binding InputText,Mode=TwoWay}" VerticalAlignment="Top" Width="239" />

奖励:如果你想拥有textBox的默认值,请务必在提交数据后设置它(例如:&#34; InputText&#34; =&#34; PlaceHolder Text Here&#34; if empty)。

makertoo answered 2019-08-13T05:20:26Z
1 votes

另一种方法;-)

这也适用于PasswordBox.如果您想使用TextBox,只需与PasswordChanged联系TextChanged

XAML:

<Grid>
    <!-- overlay with hint text -->
    <TextBlock Margin="5,2"
                Text="Password"
                Foreground="Gray"
                Name="txtHintPassword"/>
    <!-- enter user here -->
    <PasswordBox Name="txtPassword"
                Background="Transparent"
                PasswordChanged="txtPassword_PasswordChanged"/>
</Grid>

代码隐藏:

private void txtPassword_PasswordChanged(object sender, RoutedEventArgs e)
{
    txtHintPassword.Visibility = Visibility.Visible;
    if (txtPassword.Password.Length > 0)
    {
        txtHintPassword.Visibility = Visibility.Hidden;
    }
}
Mat answered 2019-08-13T05:21:07Z
1 votes

我曾经遇到过同样的情况,我按照方式解决了。我只满足了提示框的要求,你可以通过在焦点等其他事件上添加效果和其他东西来使其更具交互性。

WPF代码(我删除了样式以使其可读)

<Grid Margin="0,0,0,0"  Background="White">
    <Label Name="adminEmailHint" Foreground="LightGray" Padding="6"  FontSize="14">Admin Email</Label>
    <TextBox Padding="4,7,4,8" Background="Transparent" TextChanged="adminEmail_TextChanged" Height="31" x:Name="adminEmail" Width="180" />
</Grid>
<Grid Margin="10,0,10,0" Background="White" >
    <Label Name="adminPasswordHint" Foreground="LightGray" Padding="6"  FontSize="14">Admin Password</Label>
    <PasswordBox Padding="4,6,4,8" Background="Transparent" PasswordChanged="adminPassword_PasswordChanged" Height="31" x:Name="adminPassword" VerticalContentAlignment="Center" VerticalAlignment="Center" Width="180" FontFamily="Helvetica" FontWeight="Light" FontSize="14" Controls:TextBoxHelper.Watermark="Admin Password"  FontStyle="Normal" />
</Grid>

C#代码

private void adminEmail_TextChanged(object sender, TextChangedEventArgs e)
    {
        if(adminEmail.Text.Length == 0)
        {
            adminEmailHint.Visibility = Visibility.Visible;
        }
        else
        {
            adminEmailHint.Visibility = Visibility.Hidden;
        }
    }

private void adminPassword_PasswordChanged(object sender, RoutedEventArgs e)
    {
        if (adminPassword.Password.Length == 0)
        {
            adminPasswordHint.Visibility = Visibility.Visible;
        }
        else
        {
            adminPasswordHint.Visibility = Visibility.Hidden;
        }
    }
Mohammad Mahroz answered 2019-08-13T05:21:47Z
0 votes

我使用了丢失的焦点事件:

Private Sub txtSearchBox_GotFocus(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles txtSearchBox.GotFocus
    If txtSearchBox.Text = "Search" Then
        txtSearchBox.Text = ""
    Else

    End If

End Sub

Private Sub txtSearchBox_LostFocus(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles txtSearchBox.LostFocus
    If txtSearchBox.Text = "" Then
        txtSearchBox.Text = "Search"
    Else

    End If
End Sub

它运作良好,但文本仍然是灰色的。 需要清理。 我使用的是VB.NET

StarLordBlair answered 2019-08-13T05:22:20Z
0 votes
  <Grid>
    <TextBox Name="myTextBox"/>
    <TextBlock>
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=myTextBox, Path=Text.IsEmpty}" Value="True">
                        <Setter Property="Text" Value="Prompt..."/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
</Grid>
DerBesondereEin answered 2019-08-13T05:22:38Z
0 votes

另一种解决方案是使用像MahApps.Metro这样的WPF工具包。 它有许多不错的功能,如文本框水印:

Controls:TextBoxHelper.Watermark="Search..."

见[http://mahapps.com/controls/textbox.html]

StefanG answered 2019-08-13T05:23:18Z
0 votes

那么使用materialDesign HintAssist呢? 我正在使用它,你也可以添加浮动提示:

<TextBox Width="150" Height="40" Text="hello" materialDesign:HintAssist.Hint="address"  materialDesign:HintAssist.IsFloating="True"></TextBox>

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

Mahdi Khalili answered 2019-08-13T05:23:52Z
-1 votes

我用VisualBrush完成了这个操作,并在Style中建议了一些触发器:sellmeadog

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

@sellmeadog:应用程序正在运行,bt设计未加载...以下错误出现:模糊类型参考。 一种名为&#39; StaticExtension&#39; 发生在至少两个名称空间中,MS.Internal.Metadata.ExposedTypes.Xaml&#39; 和&#39; System.Windows.Markup&#39;。 考虑调整程序集XmlnsDefinition属性。使用.net 3.5

SUHAIL AG answered 2019-08-13T05:24:26Z
-10 votes

对于WPF,没有办法。 你必须模仿它。 看这个例子。 辅助(片状解决方案)是托管从TextBox继承的WinForms用户控件,并将EM_SETCUEBANNER消息发送到编辑控件。即。

[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);
}

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

如果您想了解更多信息,请参阅以下有关BitFlex的文章。 您将开始发现,如果您希望使用Windows资源管理器样式控件,这通常永远不会开箱即用,并且因为WPF通常不能使用句柄,所以您无法在Win32或现有控件之间编写简单的包装,就像您可以 使用WinForms。

截图:enter image description here

David Anderson answered 2019-08-13T05:25:11Z
translate from https://stackoverflow.com:/questions/7425618/how-can-i-add-a-hint-text-to-wpf-textbox