WPF textbox and PasswordBox add watermark _c# Tutorial

Source: Internet
Author: User
Tags visibility


The example of this article for everyone to share the TextBox and PasswordBox watermark method for your reference, the specific contents are as follows



TextBox plus watermark



TextBox plus watermark, need a visualbrush and trigger to verify that the text is empty, set the background in the empty brush can realize the watermark effect.


<TextBox Name="txtBoxName" Width="120" Height="23">
      <TextBox.Resources>
        <VisualBrush x:Key="HelpBrush" TileMode="None" Opacity="0.3" Stretch="None" AlignmentX="Left">
          <VisualBrush.Visual>
            <TextBlock FontStyle="Italic" Text="Watermark effect"/>
          </VisualBrush.Visual>
        </VisualBrush>
      </TextBox.Resources>
      <TextBox.Style>
        <Style TargetType="TextBox">
          <Setter Property="Height" Value="23"/>
          <Setter Property="HorizontalAlignment" Value="Left"/>
          <Setter Property="VerticalAlignment" Value="Top"/>
          <Style.Triggers>
            <Trigger Property="Text" Value="{x:Null}">
              <Setter Property="Background" Value="{StaticResource HelpBrush}"/>
            </Trigger>
            <Trigger Property="Text" Value="">
              <Setter Property="Background" Value="{StaticResource HelpBrush}"/>
            </Trigger>
          </Style.Triggers>
        </Style>
      </TextBox.Style>
    </TextBox>


PasswordBox Plus watermark



PasswordBox watermark, you need to add a decision to enter a Non-empty dependency property because the PasswordBox itself does not have this attribute.



By a passwordlength function to determine the length of the password box is not 0, if it is 0 to display a background watermark, otherwise hidden.



Attribute part code, CS file


public class PasswordBoxMonitor : DependencyObject
  {
    public static bool GetIsMonitoring(DependencyObject obj)
    {
      return (bool)obj.GetValue(IsMonitoringProperty);
    }

    public static void SetIsMonitoring(DependencyObject obj, bool value)
    {
      obj.SetValue(IsMonitoringProperty, value);
    }

    public static readonly DependencyProperty IsMonitoringProperty =
      DependencyProperty.RegisterAttached("IsMonitoring", typeof(bool), typeof(PasswordBoxMonitor), new UIPropertyMetadata(false, OnIsMonitoringChanged));



    public static int GetPasswordLength(DependencyObject obj)
    {
      return (int)obj.GetValue(PasswordLengthProperty);
    }

    public static void SetPasswordLength(DependencyObject obj, int value)
    {
      obj.SetValue(PasswordLengthProperty, value);
    }

    public static readonly DependencyProperty PasswordLengthProperty =
      DependencyProperty.RegisterAttached("PasswordLength", typeof(int), typeof(PasswordBoxMonitor), new UIPropertyMetadata(0));

    private static void OnIsMonitoringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      var pb = d as PasswordBox;
      if (pb == null)
      {
        return;
      }
      if ((bool)e.NewValue)
      {
        pb.PasswordChanged += PasswordChanged;
      }
      else
      {
        pb.PasswordChanged -= PasswordChanged;
      }
    }

    static void PasswordChanged(object sender, RoutedEventArgs e)
    {
      var pb = sender as PasswordBox;
      if (pb == null)
      {
        return;
      }
      SetPasswordLength(pb, pb.Password.Length);
    }
  }





Xmal Code


<PasswordBox Name="pb" Width="120" VerticalAlignment="Bottom" Height="35">
      <PasswordBox.Style>
        <Style TargetType="PasswordBox">
          <Setter Property="Height" Value="23"/>
          <Setter Property="HorizontalAlignment" Value="Left"/>
          <Setter Property="VerticalAlignment" Value="Top"/>
          <Setter Property="local:PasswordBoxMonitor.IsMonitoring" Value="True"/>
          <Setter Property="Template">
            <Setter.Value>
              <ControlTemplate TargetType="{x:Type PasswordBox}">
                <Border Name="Bd" Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" SnapsToDevicePixels="True">
                  <Grid>
                    <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    <StackPanel Orientation="Horizontal" Visibility="Collapsed" Name="myStackPanel">
                      <TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="LightGray" Text="水印效果"/>
                    </StackPanel>
                  </Grid>
                </Border>
                <ControlTemplate.Triggers>
                  <Trigger Property="IsEnabled" Value="false">
                    <Setter Property="Visibility" TargetName="myStackPanel" Value="Collapsed"/>
                  </Trigger>
                  <Trigger Property="local:PasswordBoxMonitor.PasswordLength" Value="0">
                    <Setter Property="Visibility" TargetName="myStackPanel" Value="Visible"/>
                  </Trigger>
                </ControlTemplate.Triggers>
              </ControlTemplate>
            </Setter.Value>
          </Setter>
        </Style>
      </PasswordBox.Style>
    </PasswordBox>








2016-09-07 New Content



Expose the TextBlock and make a TextBox control that can modify the watermark


<TextBox x:Class="OracleCodeGenerator.watermarkTextBox"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
       xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
       xmlns:local="clr-namespace:OracleCodeGenerator"
       mc:Ignorable="d" 
       d:DesignHeight="300" d:DesignWidth="300" Name="tb">
  <TextBox.Resources>
    <VisualBrush x:Key="HelpBrush" TileMode="None" Opacity="0.3" Stretch="None" AlignmentX="Left">
      <VisualBrush.Visual>
        <TextBlock Text="{Binding TbText,ElementName=tb}" FontStyle="Italic"/>
      </VisualBrush.Visual>
    </VisualBrush>
  </TextBox.Resources>
  <TextBox.Style>
    <Style TargetType="TextBox">
      <Setter Property="Height" Value="23"/>
      <Setter Property="HorizontalAlignment" Value="Left"/>
      <Setter Property="VerticalAlignment" Value="Top"/>
      <Style.Triggers>
        <Trigger Property="Text" Value="{x:Null}">
          <Setter Property="Background" Value="{StaticResource HelpBrush}"/>
        </Trigger>
        <Trigger Property="Text" Value="">
          <Setter Property="Background" Value="{StaticResource HelpBrush}"/>
        </Trigger>
      </Style.Triggers>
    </Style>
  </TextBox.Style>
</TextBox>


 
public partial class watermarkTextBox : TextBox
  {
    public watermarkTextBox()
    {
      InitializeComponent();
    }

    private string tbText;

    public string TbText
    {
      get
      {
        return tbText;
      }

      set
      {
        tbText = value;
      }
    }
  }


Call only a word





Copy Code code as follows:
<local:watermarktextbox width= "tbtext=" I am a watermark/>





The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.