一、简单设置水印TextBox控件,废话不多说看代码:

  1. <TextBox TextWrapping="Wrap" Margin="10" Height="69" Visibility="Visible">
  2. <TextBox.Style>
  3. <Style TargetType="TextBox">
  4. <Style.Triggers>
  5. <MultiTrigger>
  6. <MultiTrigger.Conditions>
  7. <Condition Property="IsFocused" Value="false"/>
  8. <Condition Property="Text" Value=""/>
  9. </MultiTrigger.Conditions>
  10. <Setter Property="Background">
  11. <Setter.Value>
  12. <VisualBrush AlignmentX="Left" AlignmentY="Top" Stretch="None">
  13. <VisualBrush.Visual>
  14. <TextBlock Padding="5 2" Background="Transparent" TextWrapping="Wrap" Height="40" Foreground="Silver">您的评价对网友有很重要的参考作用,请认真填<LineBreak/>写,谢谢合作!</TextBlock>
  15. </VisualBrush.Visual>
  16. </VisualBrush>
  17. </Setter.Value>
  18. </Setter>
  19. </MultiTrigger>
  20. </Style.Triggers>
  21. </Style>
  22. </TextBox.Style>
  23. </TextBox>

这里的style可以单独提出来,方便多处使用。

设置之后的效果如下:

二、扩展增强TextBox

有的时候会碰到TextBox里面需要添加按钮,或者TextBox需要设置圆角。这个时候就需要添加自定义控件,添加依赖属性来扩展功能了。

2.1 添加自定义控件TextBoxEx

代码如下:

  1. public class TextBoxEx : TextBox
  2. {
  3. static TextBoxEx()
  4. {
  5. DefaultStyleKeyProperty.OverrideMetadata(typeof(TextBoxEx), new FrameworkPropertyMetadata(typeof(TextBoxEx)));
  6. }
  7.  
  8. public TextBoxEx()
  9. {
  10. CommandBindings.Add(new CommandBinding(SearchClickCommand, delegate
  11. {
  12. SearchClick?.Invoke(this, null);
  13. }));
  14. }
  15.  
  16. public static RoutedUICommand SearchClickCommand = new RoutedUICommand(nameof(SearchClickCommand), nameof(SearchClickCommand), typeof(RoutedUICommand));
  17.  
  18. public event EventHandler SearchClick;
  19. public string WaterMark
  20. {
  21. get { return (string)GetValue(WaterMarkProperty); }
  22. set { SetValue(WaterMarkProperty, value); }
  23. }
  24.  
  25. public static readonly DependencyProperty WaterMarkProperty =
  26. DependencyProperty.Register("WaterMark", typeof(string), typeof(TextBoxEx), new PropertyMetadata(null));
  27.  
  28. public ImageSource Icon
  29. {
  30. get { return (ImageSource)GetValue(IconProperty); }
  31. set { SetValue(IconProperty, value); }
  32. }
  33.  
  34. public static readonly DependencyProperty IconProperty =
  35. DependencyProperty.Register("Icon", typeof(ImageSource), typeof(TextBoxEx), new PropertyMetadata(null));
  36.  
  37. public new Brush BorderBrush
  38. {
  39. get { return (Brush)GetValue(BorderBrushProperty); }
  40. set { SetValue(BorderBrushProperty, value); }
  41. }
  42.  
  43. public static readonly new DependencyProperty BorderBrushProperty =
  44. DependencyProperty.Register("BorderBrush", typeof(Brush), typeof(TextBoxEx), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(,,))));
  45.  
  46. public Brush MouseOverBorderBrush
  47. {
  48. get { return (Brush)GetValue(MouseOverBorderBrushProperty); }
  49. set { SetValue(MouseOverBorderBrushProperty, value); }
  50. }
  51.  
  52. public static readonly DependencyProperty MouseOverBorderBrushProperty =
  53. DependencyProperty.Register("MouseOverBorderBrush", typeof(Brush), typeof(TextBoxEx), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(,,))));
  54.  
  55. public new Brush Background
  56. {
  57. get { return (Brush)GetValue(BackgroundProperty); }
  58. set { SetValue(BackgroundProperty, value); }
  59. }
  60.  
  61. public static readonly new DependencyProperty BackgroundProperty =
  62. DependencyProperty.Register("Background", typeof(Brush), typeof(TextBoxEx), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(,,))));
  63.  
  64. public Brush MouseOverBackground
  65. {
  66. get { return (Brush)GetValue(MouseOverBackgroundProperty); }
  67. set { SetValue(MouseOverBackgroundProperty, value); }
  68. }
  69.  
  70. public static readonly DependencyProperty MouseOverBackgroundProperty =
  71. DependencyProperty.Register("MouseOverBackground", typeof(Brush), typeof(TextBoxEx), new PropertyMetadata(Color.FromRgb(,,)));
  72.  
  73. public CornerRadius CornerRadius
  74. {
  75. get { return (CornerRadius)GetValue(CornerRadiusProperty); }
  76. set { SetValue(CornerRadiusProperty, value); }
  77. }
  78.  
  79. public static readonly DependencyProperty CornerRadiusProperty =
  80. DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(TextBoxEx), new PropertyMetadata(new CornerRadius()));
  81.  
  82. public IconDirection IconDirection
  83. {
  84. get { return (IconDirection)GetValue(IconDirectionProperty); }
  85. set { SetValue(IconDirectionProperty, value); }
  86. }
  87.  
  88. public static readonly DependencyProperty IconDirectionProperty =
  89. DependencyProperty.Register("IconDirection", typeof(IconDirection), typeof(TextBoxEx), new PropertyMetadata(IconDirection.Right));
  90.  
  91. }
  92.  
  93. public enum IconDirection
  94. {
  95. Left,
  96. Right
  97. }

2.2 设置TextBoxEx样式

  1. <Style TargetType="{x:Type local:TextBoxEx}">
  2. <Setter Property="Foreground" Value="#555558"/>
  3. <Setter Property="Background" Value="#6a675a"/>
  4. <Setter Property="Template">
  5. <Setter.Value>
  6. <ControlTemplate TargetType="{x:Type local:TextBoxEx}">
  7. <Border x:Name="_border" CornerRadius="{TemplateBinding CornerRadius}" Padding="{TemplateBinding CornerRadius,Converter={StaticResource cornerRadiusToThickness} }" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True">
  8. <Grid>
  9. <Grid.ColumnDefinitions>
  10. <ColumnDefinition x:Name="columleft" Width="auto"/>
  11. <ColumnDefinition Width="*"/>
  12. <ColumnDefinition x:Name="columright" Width="auto"/>
  13. </Grid.ColumnDefinitions>
  14. <Image Source="{TemplateBinding Icon}" Cursor="Hand" Stretch="None" VerticalAlignment="Center" HorizontalAlignment="Center">
  15. <i:Interaction.Triggers>
  16. <i:EventTrigger EventName="MouseLeftButtonUp">
  17. <i:InvokeCommandAction Command="local:TextBoxEx.SearchClickCommand"/>
  18. </i:EventTrigger>
  19. </i:Interaction.Triggers>
  20. </Image>
  21. <ScrollViewer x:Name="PART_ContentHost" VerticalAlignment="Center" Foreground="{TemplateBinding Foreground}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Grid.Column="1"/>
  22. <TextBlock x:Name="_txtWater" IsHitTestVisible="False" Margin="3 0 0 0" VerticalAlignment="Center" Foreground="#9f9f9f" Text="{TemplateBinding WaterMark}" Visibility="Hidden" Grid.Column="1"/>
  23. <Image Source="{TemplateBinding Icon}" Cursor="Hand" Stretch="None" Grid.Column="2" VerticalAlignment="Center" HorizontalAlignment="Center">
  24. <i:Interaction.Triggers>
  25. <i:EventTrigger EventName="MouseLeftButtonUp">
  26. <i:InvokeCommandAction Command="local:TextBoxEx.SearchClickCommand"/>
  27. </i:EventTrigger>
  28. </i:Interaction.Triggers>
  29. </Image>
  30. </Grid>
  31. </Border>
  32. <ControlTemplate.Triggers>
  33. <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}" Value="">
  34. <Setter TargetName="_txtWater" Property="Visibility" Value="Visible" />
  35. </DataTrigger>
  36. <Trigger Property="IsEnabled" Value="False">
  37. <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
  38. </Trigger>
  39. <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=IconDirection}" Value="Left">
  40. <Setter TargetName="columright" Property="Width" Value="0" />
  41. </DataTrigger>
  42. <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=IconDirection}" Value="Right">
  43. <Setter TargetName="columleft" Property="Width" Value="0" />
  44. </DataTrigger>
  45. <Trigger Property="IsMouseOver" Value="True">
  46. <Setter Property="BorderBrush" Value="{Binding MouseOverBorderBrush,RelativeSource={RelativeSource TemplatedParent}}"/>
  47. <Setter Property="Background" Value="{Binding MouseOverBackground,RelativeSource={RelativeSource TemplatedParent}}"/>
  48. </Trigger>
  49. </ControlTemplate.Triggers>
  50. </ControlTemplate>
  51. </Setter.Value>
  52. </Setter>
  53. </Style>

这里面使用了一个转换器cornerRadiusToThickness,转换器的作用是当TextBox设置了圆角之后,保证TextBox里的内容不溢出圆角。WPF转换器的使用大家可以百度。

转换器的内容如下:

  1. public class CornerRadiusToThickness : IValueConverter
  2. {
  3. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  4. {
  5. Thickness result = new Thickness();
  6. if (value is CornerRadius)
  7. {
  8. var tem = (CornerRadius)value;
  9. result = new Thickness(tem.TopLeft, , tem.TopRight, );
  10. }
  11. return result;
  12. }
  13.  
  14. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  15. {
  16. throw new NotImplementedException();
  17. }
  18. }

另外为了触发TextBox按钮的单击事件,添加了这个两个dll文件引用,Microsoft.Expression.Interactions.dll和System.Windows.Interactivity.dll。

在顶部定义 xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

2.3 引用方法

  1. <local:TextBoxEx WaterMark="请输入搜索内容..." SearchClick="TextBoxEx_SearchClick" KeyDown="TextBoxEx_KeyDown" Background="#dfe1e3" VerticalAlignment="Center" MouseOverBackground="#dfe1e3" CornerRadius="13.5" IconDirection="Right" Icon="/Images/Title/search.png" Height="25" />

所有代码已经上传到github:https://github.com/caomfan/WpfDemo.git

WPF 自定义TextBox带水印控件,可设置圆角的更多相关文章

  1. WPF自定义LED风格数字显示控件

    原文:WPF自定义LED风格数字显示控件 版权声明:本文为博主原创文章,转载请注明作者和出处 https://blog.csdn.net/ZZZWWWPPP11199988899/article/de ...

  2. 【C#】wpf自定义calendar日期选择控件的样式

    原文:[C#]wpf自定义calendar日期选择控件的样式 首先上图看下样式 原理 总览 ItemsControl内容的生成 实现 界面的实现 后台ViewModel的实现 首先上图,看下样式 原理 ...

  3. WPF 自定义ItemsControl/ListBox/ListView控件样式

    一.前言 ItemsControl.ListBox.ListView这三种控件在WPF中都可作为列表信息展示控件.我们可以通过修改这三个控件的样式来展示我们的列表信息. 既然都是展示列表信息的控件,那 ...

  4. WPF自定义TextBox及ScrollViewer

    原文:WPF自定义TextBox及ScrollViewer 寒假过完,在家真心什么都做不了,可能年龄大了,再想以前那样能专心坐下来已经不行了.回来第一件事就是改了项目的一个bug,最近又新增了一个新的 ...

  5. WPF Timeline简易时间轴控件的实现

    原文:WPF Timeline简易时间轴控件的实现 效果图: 由于整个控件是实现之后才写的教程,因此这里记录的代码是最终实现后的,前后会引用到其他的一些依赖属性或者代码,需要阅读整篇文章. 1.确定T ...

  6. android - 自定义(组合)控件 + 自定义控件外观

    转载:http://www.cnblogs.com/bill-joy/archive/2012/04/26/2471831.html android - 自定义(组合)控件 + 自定义控件外观   A ...

  7. WPF自定义控件(一)の控件分类

    一.什么是控件(Controls) 控件是指对数据和方法的封装.控件可以有自己的属性和方法,其中属性是控件数据的简单访问者,方法则是控件的一些简单而可见的功能.控件创建过程包括设计.开发.调试(就是所 ...

  8. Android创建自定义的布局和控件

    Android的自带布局有framelayout.linerlayout.relativelayout,外加两个百分比布局,但是这些无法灵活的满足我们的需要,所以我们要自己自定义并引入自己的布局.首先 ...

  9. WindowsXamlHost:在 WPF 中使用 UWP 的控件(Windows Community Toolkit)

    Windows Community Toolkit 再次更新到 5.0.以前可以在 WPF 中使用有限的 UWP 控件,而现在有了 WindowsXamlHost,则可以使用更多 UWP 原生控件了. ...

随机推荐

  1. Redis进阶实践之十八 使用管道模式加速Redis查询

    一.引言             学习redis 也有一段时间了,该接触的也差不多了.后来有一天,以为同事问我,如何向redis中批量的增加数据,肯定是大批量的,为了这主题,我从新找起了解决方案.目前 ...

  2. C# Redis实战(五)

    五.删除数据 在C# Redis实战(四)中讲述了如何在Redis中写入key-value型数据,本篇将讲述如何删除Redis中数据. 1.void Delete(T entity);删除函数的运用 ...

  3. Oracle用户、授权、角色管理

    创建和删除用户是Oracle用户管理中的常见操作,但这其中隐含了Oracle数据库系统的系统权限与对象权限方面的知识.掌握还Oracle用户的授权操作和原理,可以有效提升我们的工作效率. Oracle ...

  4. 用MATLAB结合四种方法搜寻罗马尼亚度假问题

    选修了cs的AI课,开始有点不适应,只能用matlab硬着头皮上了,不过matlab代码全网仅此一份,倒有点小自豪. 一.练习题目 分别用宽度优先.深度优先.贪婪算法和 A*算法求解"罗马利 ...

  5. 记一次 synchronized 锁字符串引发的坑兼再谈 Java 字符串

    业务有一个需求,我把问题描述一下: 通过代理IP访问国外某网站N,每个IP对应一个固定的网站N的COOKIE,COOKIE有失效时间. 并发下,取IP是有一定策略的,取到IP之后拿IP对应的COOKI ...

  6. const 相关知识 const和指针、const和引用

    以前老是对const概念不清不楚,今天算是好好做个笔记总结一下.以下内容包括1)常量指针(指针本身是常量),2)指针常量(指针指向的是常量对象),3)常量引用,4)const成员函数. 常量指针,指针 ...

  7. Adriod与HTML+JS的交互

    本篇主要实现的功能点: Android 调用HTML中的javascript脚本 HTML中的javascript脚本调用Android本地代码 Android 调用HTML中的javascript脚 ...

  8. 学习java第一章

    本人是一名5年工作的人了,出来社会也比较早,工作经验比起刚刚出社会的大学生要和很多了,知道社会的现实与无奈,我为什么选择想学java昵,肯定受到了朋友的影响的,接下来就讲讲我学习java的过程. 1. ...

  9. python 信号处理

    linux开发中,通常会在进程中设置专门的信号处理方法,比如经常使用的CTRL+C,KILL等信号.如果你熟悉liunx编程,那么python等信号处理方法对你来说就很简单,下面的内容将主要介绍pyt ...

  10. web服务器学习2---httpd-2.4.29虚拟目录及访问控制

    一 创建虚拟目录 环境准备: 系统:CentOS 7.4 软件:httpd-2.4.29 1.编辑主配置文件,添加命令运行子配置文件 vi /usr/local/httpd/conf/httpd.co ...