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


当前回答

下面是XAML中另一个简单的解决方案:

XAML:

       <TextBox>
            <TextBox.Resources>
                <Style TargetType="TextBox">
                    <Style.Triggers>
                        <Trigger Property="IsFocused" Value="True">
                            <!--text color-->
                            <Setter Property="Foreground" Value="Black"/>
                            <Setter Property="Text" Value=""/>
                        </Trigger>
                        <Trigger Property="IsFocused" Value="False">
                            <!--placeholder color-->
                            <Setter Property="Foreground" Value="Gray"/>
                            <!--placeholder here-->
                            <Setter Property="Text" Value="Placeholder"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Resources>
        </TextBox>

其他回答

我已经创建了一个简单的代码实现,它适用于WPF和Silverlight:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

public class TextBoxWatermarked : TextBox
{
    #region [ Dependency Properties ]

    public static DependencyProperty WatermarkProperty = DependencyProperty.Register
    (
         "Watermark",
         typeof(string),
         typeof(TextBoxWatermarked),
         new PropertyMetadata(new PropertyChangedCallback(OnWatermarkChanged))
    );
    
    #endregion
    
    
    #region [ Fields ]
    
    private bool _isWatermarked;
    private Binding _textBinding;

    #endregion


    #region [ Properties ]

    protected new Brush Foreground
    {
        get { return base.Foreground; }
        set { base.Foreground = value; }
    }

    public string Watermark
    {
        get { return (string)GetValue(WatermarkProperty); }
        set { SetValue(WatermarkProperty, value); }
    }

    #endregion


    #region [ .ctor ]
    
    public TextBoxWatermarked()
    {
        Loaded += (s, ea) => ShowWatermark();
    }
    
    #endregion


    #region [ Event Handlers ]

    protected override void OnGotFocus(RoutedEventArgs e)
    {
        base.OnGotFocus(e);
        HideWatermark();
    }
    
    protected override void OnLostFocus(RoutedEventArgs e)
    {
        base.OnLostFocus(e);
        ShowWatermark();
    }
    
    private static void OnWatermarkChanged(DependencyObject sender, DependencyPropertyChangedEventArgs ea)
    {
        var tbw = sender as TextBoxWatermarked;
        if (tbw == null) return;
        tbw.ShowWatermark();
    }

    #endregion


    #region [ Methods ]

    private void ShowWatermark()
    {
        if (string.IsNullOrEmpty(base.Text))
        {
            _isWatermarked = true;
            base.Foreground = new SolidColorBrush(Colors.Gray);
            var bindingExpression = GetBindingExpression(TextProperty);
            _textBinding = bindingExpression == null ? null : bindingExpression.ParentBinding;
            if (bindingExpression != null)
                bindingExpression.UpdateSource();
            SetBinding(TextProperty, new Binding());
            base.Text = Watermark;
        }
    }

    private void HideWatermark()
    {
        if (_isWatermarked)
        {
            _isWatermarked = false;
            ClearValue(ForegroundProperty);
            base.Text = "";
            SetBinding(TextProperty, _textBinding ?? new Binding());
        }
    }

    #endregion
}

用法:

<TextBoxWatermarked Watermark="Some text" />

CodeProject上有一篇关于如何在“3行XAML”中做到这一点的文章。

<Grid Background="{StaticResource brushWatermarkBackground}">
  <TextBlock Margin="5,2" Text="Type something..."
             Foreground="{StaticResource brushForeground}"
             Visibility="{Binding ElementName=txtUserEntry, Path=Text.IsEmpty,
                          Converter={StaticResource BooleanToVisibilityConverter}}" />
  <TextBox Name="txtUserEntry" Background="Transparent"
           BorderBrush="{StaticResource brushBorder}" />
</Grid>

好吧,它可能不是3行XAML格式的,但它非常简单。

需要注意的一点是:文本上的IsEmpty属性不是string的属性,而是ICollectionView的属性,并且可以显式地设置为Path=Text.(componentModel:ICollectionView.IsEmpty) (with xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase")。这里有详细的解释。

使用风格的简单解决方案:

<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="MM:SS:HH AM/PM" 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>

伟大的解决方案:

https://code.msdn.microsoft.com/windowsdesktop/In-place-hit-messages-for-18db3a6c

最简单的方法水印的文本框

 <Window.Resources>
    <Style x:Key="MyWaterMarkStyle" TargetType="{x:Type TextBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Grid>
                        <Border Background="White" BorderBrush="#FF7D8683" BorderThickness="1"/>
                        <ScrollViewer x:Name="PART_ContentHost" Margin="5,0,0,0" VerticalAlignment="Center" />
                        <Label Margin="5,0,0,0" x:Name="WaterMarkLabel" Content="{TemplateBinding Tag}" VerticalAlignment="Center"
                           Visibility="Collapsed" Foreground="Gray" FontFamily="Arial"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="Text" Value=""/>
                            </MultiTrigger.Conditions>
                            <Setter Property="Visibility" TargetName="WaterMarkLabel" Value="Visible"/>
                        </MultiTrigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Foreground" Value="DimGray"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

并添加文本框StaticResource样式

  <TextBox
                Style="{StaticResource MyWaterMarkStyle}"
                Tag="Search Category"
                Grid.Row="0"
                Text="{Binding CategorySearch,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                TextSearch.Text="Search Category"
                >

看看另一个简单的解决方案:

我专注于“得到专注”和“失去专注”事件。

XAML:

<Grid>
<TextBlock x:Name="DosyaİhtivaEdenDizinYansıması" Text="Hedef Dizin Belirtin" VerticalAlignment="Center" HorizontalAlignment="Center" TextAlignment="Center" Foreground="White" Background="Transparent" Width="500" MinWidth="300" Margin="10,0,0,0" Opacity="0.7"/>
<TextBox x:Name="DosyaİhtivaEdenDizin" CaretBrush="White" Foreground="White" Background="Transparent" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center" MinHeight="40" BorderThickness="1" BorderBrush="White" Width="500" MinWidth="300" Margin="10,0,0,0" GotFocus="DosyaİhtivaEdenDizin_GotFocus" LostFocus="DosyaİhtivaEdenDizin_LostFocus"/>
</Grid>

C#:

    #region DosyaİhtivaEdenDizin
    private void DosyaİhtivaEdenDizin_GotFocus(object sender, RoutedEventArgs e)
    {
        if (DosyaİhtivaEdenDizin.Text.Length == 0)
        {
            DosyaİhtivaEdenDizinYansıması.Text = "";
        }
    }

    private void DosyaİhtivaEdenDizin_LostFocus(object sender, RoutedEventArgs e)
    {
        if (DosyaİhtivaEdenDizin.Text.Length == 0)
        {
            DosyaİhtivaEdenDizinYansıması.Text = "Hedef Dizin Belirtin";
        }
    }
    #endregion