WPF TextBox添加水印提示

        在进行一些输入提示时,使用水印的效果是好于再使用一个Label添加内容的。看下如下效果:

WPF TextBox添加水印提示_第1张图片

觉得有用的小伙伴可以继续往下看。 

        我这个测试Demo是WPF + MVVM的。输入名称做了一个数据绑定。以下是代码,最后我把工程地址也加上。供大家免费下载。

Window.xaml.cs


    
        
            
                
            
        
        
    
    
        
            
            
            
        
        
        
        
        
            
            
        
    

Window.cs


using System.Windows;


namespace TextBoxVerification
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        ViewModel ViewModel;
        public MainWindow()
        {
            InitializeComponent();
            ViewModel = new ViewModel();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.DataContext = ViewModel;
            ViewModel.PersonID = "456";
        }
    }
}

NotifyObject.cs(数据绑定使用)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TextBoxVerification
{
    public class NotifyObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        /// 
        /// 属性发生改变时调用该方法发出通知
        /// 
        /// 属性名称
        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected virtual void SetAndNotifyIfChanged(string propertyName, ref T oldValue, T newValue)
        {
            if (oldValue == null && newValue == null) return;
            if (oldValue != null && oldValue.Equals(newValue)) return;
            if (newValue != null && newValue.Equals(oldValue)) return;
            oldValue = newValue;
            RaisePropertyChanged(propertyName);
        }
    }
}

ViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TextBoxVerification
{
    class ViewModel : NotifyObject
    {
        private string _personID = "123";
        public string PersonID
        {
            get { return _personID; }
            set
            {
                _personID = value;
                RaisePropertyChanged("PersonID");
            }
        }
    }
}

免费工程下载路径:https://download.csdn.net/download/chulijun3107/87647332

你可能感兴趣的:(wpf,MVVM)