WPF 水印 TextBox MaskedTextBox

设计出来的样子是这个样子的。

注:这是个封装在DLL中的控件,但不影响理解


一、样式字典 - 仅仅定义了基本的骨骼结构

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    
                    >
    <!--该字典中除非特殊声明,否则资源一律不能删除,会照成异常,因动态改变资源所以请务必不要随便改变动态资源为静态-->
    
    <!--TextBox视图-->
    <VisualBrush x:Key="TextBoxVisual">
        <VisualBrush.Visual>
            <TextBlock></TextBlock>
        </VisualBrush.Visual>
    </VisualBrush>
    <!--TextBoxMasked样式-->
    <Style TargetType="TextBox" x:Key="TextBoxStyle">
        <Style.Triggers>
            <Trigger Property="Text" Value="{x:Null}">
                <Setter Property="Background" Value="{DynamicResource TextBoxVisual}"></Setter>
            </Trigger>
            <Trigger Property="Text" Value="">
                <Setter Property="Background" Value="{DynamicResource TextBoxVisual}"></Setter>
            </Trigger>
            <Trigger Property="IsFocused" Value="True">
                <Setter Property="Background" Value="{x:Null}"></Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
</ResourceDictionary>

二、控件的封装:定义了几个依赖属性用于界面设置


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace DialogEx.Controls
{
    /// <summary>
    /// 水印TextBox
    /// </summary>
    public class TextBoxMasked : TextBox
    {
        #region 依赖属性
        
        public static readonly DependencyProperty MaskTextProperty = DependencyProperty.Register("MaskText", typeof(string), typeof(TextBoxMasked),new PropertyMetadata(string.Empty));
        public static readonly DependencyProperty MaskTextFontStyleProperty = DependencyProperty.Register("MaskFontStyle", typeof(FontStyle), typeof(TextBoxMasked),new PropertyMetadata(FontStyles.Italic));
        public static readonly DependencyProperty MaskTextVerticalContentProperty = DependencyProperty.Register("MaskVerticalContent", typeof(AlignmentY), typeof(TextBoxMasked), new PropertyMetadata(AlignmentY.Center));
        public static readonly DependencyProperty MaskTextHorizontalAlignmentContentProperty = DependencyProperty.Register("MaskHorizontalContent", typeof(AlignmentX), typeof(TextBoxMasked), new PropertyMetadata(AlignmentX.Left));
        public static readonly DependencyProperty MaskTextFontSizeProperty = DependencyProperty.Register("MaskFontSize", typeof(Double), typeof(TextBoxMasked), new PropertyMetadata((Double)12));
        public static readonly DependencyProperty MaskTextLineHeightProperty = DependencyProperty.Register("MaskLineHeight", typeof(Double), typeof(TextBoxMasked), new PropertyMetadata((Double)12));
        #endregion

        #region 公有字段
        /// <summary>
        /// 内容
        /// </summary>
        public string MaskedText
        {
            get { return ((string)GetValue(MaskTextProperty)).Replace("\\r\\n", "\r\n"); }
            set { SetValue(MaskTextProperty, value); }
        }

        /// <summary>
        /// 字体样式
        /// </summary>
        public FontStyle MaskFontStyle
        {
            get { return (FontStyle)GetValue(MaskTextFontStyleProperty); }
            set { SetValue(MaskTextFontStyleProperty, value); }
        }

        /// <summary>
        /// 字体大小
        /// </summary>
        public double MaskFontSize
        {
            get { return (double)GetValue(MaskTextFontSizeProperty); }
            set { SetValue(MaskTextFontSizeProperty, value); }
        }

        /// <summary>
        /// 字体大小
        /// </summary>
        public double MaskLineHeight
        {
            get { return (double)GetValue(MaskTextLineHeightProperty); }
            set { SetValue(MaskTextLineHeightProperty, value); }
        }

        /// <summary>
        /// 垂直位置
        /// </summary>
        public AlignmentY MaskVerticalContent
        {
            get { return (AlignmentY)GetValue(MaskTextVerticalContentProperty); }
            set { SetValue(MaskTextVerticalContentProperty, value); }
        }

        /// <summary>
        /// 水平位置
        /// </summary>
        public AlignmentX MaskHorizontalContent
        {
            get { return (AlignmentX)GetValue(MaskTextHorizontalAlignmentContentProperty); }
            set { SetValue(MaskTextHorizontalAlignmentContentProperty, value); }
        }
        #endregion

        #region 私有字段
        
        #endregion

        public TextBoxMasked()
        {
            Loaded += (sender, args) =>
            {
                //资源视图
                VisualBrush _MaskVisual = new VisualBrush()
                {
                    TileMode = TileMode.None,
                    Opacity = 0.3,
                    Stretch = Stretch.None,
                    AlignmentX = this.MaskHorizontalContent,
                    AlignmentY = this.MaskVerticalContent
                };
                _MaskVisual.Visual = new TextBlock()
                {
                    FontStyle = this.MaskFontStyle,
                    FontSize = this.MaskFontSize,
                    Text = this.MaskedText,
                    LineHeight = this.MaskLineHeight,
                };
               
                资源引用
                //this.Resources.Add("HelperBrush", _MaskVisual);

                //#region 触发器Setter
                //Setter NullSetter = new Setter()
                //{
                //    Property = BackgroundProperty,
                //    Value = this.Resources["HelperBrush"]
                //};
                //Setter EmptySetter = new Setter()
                //{
                //    Property = BackgroundProperty,
                //    Value = this.Resources["HelperBrush"]
                //};
                //Setter FocusedSetter = new Setter()
                //{
                //    Property = BackgroundProperty,
                //    Value = null
                //};
                //#endregion

                //#region 触发器
                //Trigger NullTrigger = new Trigger()
                //{
                //    Property = TextProperty,
                //    Value = null
                //};
                //NullTrigger.Setters.Add(NullSetter);

                //Trigger EmptyTrigger = new Trigger()
                //{
                //    Property = TextProperty,
                //    Value = ""
                //};
                //EmptyTrigger.Setters.Add(EmptySetter);

                //Trigger FocusedTrigger = new Trigger()
                //{
                //    Property = IsFocusedProperty,
                //    Value = true
                //};
                //FocusedTrigger.Setters.Add(FocusedSetter);
                //#endregion

                //#region 样式
                //Style NewStyle = new Style();
                //NewStyle.TargetType = typeof(TextBox);
                //NewStyle.Triggers.Add(NullTrigger);
                //NewStyle.Triggers.Add(EmptyTrigger);
                //NewStyle.Triggers.Add(FocusedTrigger);

                //this.Style = NewStyle;
                //#endregion

                this.Resources.Source = new Uri("DialogEx;Component/Controls/TextBoxMasked.xaml", UriKind.RelativeOrAbsolute);
                this.Resources["TextBoxVisual"] = _MaskVisual;
                this.Style = this.Resources["TextBoxStyle"] as Style;
            };
        }
    }
}


三、使用方法 - 引用文本框的命名空间。

xmlns:MyControls="clr-namespace:DialogEx.Controls;assembly=DialogEx"

<MyControls:TextBoxMasked Height="28" Width="350" VerticalContentAlignment="Center" BorderBrush="#197CD6" BorderThickness="1" Text="{Binding SearchText}" Foreground="Black" FontSize="12" MaskedText="请输入搜索关键词" MaskFontStyle="Italic" MaskVerticalContent="Center"/>



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF (Windows Presentation Foundation)是一种用于创建 Windows 桌面应用程序的技术。MVVM (Model-View-ViewModel) 是一种设计模式,用于分离应用程序的逻辑、数据和界面。 要在WPF应用程序中使用MVVM模式实现TextBox的功能,你可以按照以下步骤操作: 1. 创建一个Model类,该类包含与TextBox相关的数据。例如,你可以创建一个名为"User"的类,其中包含一个名为"Name"的属性来表示用户输入的文本。 2. 创建一个ViewModel类,该类充当Model和View之间的中间层。ViewModel类应该包含一个可绑定的属性,用于将TextBox中的文本与Model中的数据进行绑定。在ViewModel中,你可以使用实现了INotifyPropertyChanged接口的属性,以便在文本更改时通知View更新。 3. 创建一个View类,该类表示用户界面。在View中,通过使用XAML语法,将TextBox与ViewModel中的属性进行绑定。这样,当用户在TextBox中输入文本时,ViewModel中的属性将自动更新。 下面是一个简单的示例: Model类: ```C# public class User { public string Name { get; set; } } ``` ViewModel类: ```C# public class UserViewModel : INotifyPropertyChanged { private User user; public UserViewModel() { user = new User(); } public string UserName { get { return user.Name; } set { if (user.Name != value) { user.Name = value; OnPropertyChanged(nameof(UserName)); } } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } ``` View中的XAML代码: ```XAML <Window x:Class="YourNamespace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:YourNamespace" Title="Your Application" Height="450" Width="800"> <Grid> <TextBox Text="{Binding UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> </Grid> </Window> ``` 请注意,上述示例只是一个简化的实现,你可以根据自己的需求进行扩展和修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值