我怎么能把一些文本放入一个文本框,这将被自动删除时,用户键入的东西在它?


当前回答

我发现这个方法非常快速和简单

<ComboBox x:Name="comboBox1" SelectedIndex="0" HorizontalAlignment="Left" Margin="202,43,0,0" VerticalAlignment="Top" Width="149">
  <ComboBoxItem Visibility="Collapsed">
    <TextBlock Foreground="Gray" FontStyle="Italic">Please select ...</TextBlock>
  </ComboBoxItem>
  <ComboBoxItem Name="cbiFirst1">First Item</ComboBoxItem>
  <ComboBoxItem Name="cbiSecond1">Second Item</ComboBoxItem>
  <ComboBoxItem Name="cbiThird1">third Item</ComboBoxItem>
</ComboBox>

也许它能帮助到任何想这么做的人

来源:http://www.admindiaries.com/displaying-a-please-select-watermark-type-text-in-a-wpf-combobox/

其他回答

嗨,我把这个任务变成了一个行为。你只需要在文本框中添加这样的东西

<i:Interaction.Behaviors>
         <Behaviors:TextBoxWatermarkBehavior Label="Test Watermark" LabelStyle="{StaticResource StyleWatermarkLabel}"/>
</i:Interaction.Behaviors>

你可以在这里找到我的博客文章

设置文本框的占位符文本在一个柔和的颜色…

public MainWindow ( )
{
    InitializeComponent ( );
    txtInput.Text = "Type something here...";
    txtInput.Foreground = Brushes.DimGray;
}

当文本框获得焦点时,清除它并更改文本颜色

private void txtInput_GotFocus ( object sender, EventArgs e )
{
    MessageBox.Show ( "got focus" );
    txtInput.Text = "";
    txtInput.Foreground = Brushes.Red;
}
<TextBox Controls:TextBoxHelper.Watermark="Watermark"/>

添加mahapps。地铁到你的项目。 将带有上述代码的文本框添加到窗口中。

当使用@john-myczek的代码绑定文本框时,我遇到了一些困难。由于TextBox在更新时不会引发焦点事件,水印将在新文本下面保持可见。为了解决这个问题,我简单地添加了另一个事件处理程序:

if (d is ComboBox || d is TextBox)
{
    control.GotKeyboardFocus += Control_GotKeyboardFocus;
    control.LostKeyboardFocus += Control_Loaded;

    if (d is TextBox)
        (d as TextBox).TextChanged += Control_TextChanged;
}


private static void Control_TextChanged(object sender, RoutedEventArgs e)
{
    var tb = (TextBox)sender;
    if (ShouldShowWatermark(tb))
    {
        ShowWatermark(tb);
    }
    else
    {
        RemoveWatermark(tb);
    }
}

你可以使用GetFocus()和LostFocus()事件来做到这一点

下面是例子:

    private void txtData1_GetFocus(object sender, RoutedEventArgs e)
    {
        if (txtData1.Text == "TextBox1abc")
        {
            txtData1.Text = string.Empty;
        }
    }

    private void txtData1_LostFocus(object sender, RoutedEventArgs e)
    {
        if (txtData1.Text == string.Empty)
        {
            txtData1.Text = "TextBox1abc";
        }
    }