WPF参考做的TextBox圆角,并且水印文字操作

1.首先进行 转换器操作(获取当前Textbox Text是否为空或者空格)

/

csharp 复制代码
// <summary>
    /// 非空验证转换器
    /// </summary>
    #region String IsNullOrEmpty
    public class IsNullOrEmptyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return string.IsNullOrEmpty((string)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }
    #endregion 
2.设置附加属性给Textbox
csharp 复制代码
   public class TextBoxHelper
    {
        #region Watermark
        public static string GetWatermark(DependencyObject obj)
        {
            return (string)obj.GetValue(WatermarkProperty);
        }
 
        public static void SetWatermark(DependencyObject obj, string value)
        {
            obj.SetValue(WatermarkProperty, value);
        }
 
        public static readonly DependencyProperty WatermarkProperty =
            DependencyProperty.RegisterAttached("Watermark", typeof(string), typeof(TextBoxHelper));
 
 
        #endregion
    } 

3,设定样式:

csharp 复制代码
  <Style x:Key="HelperTextWaterCanEdit" TargetType="{x:Type TextBox}">
        <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
        <Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border}"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
        <Setter Property="HorizontalContentAlignment" Value="Left"/>
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="AllowDrop" Value="true"/>
        <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
        <Setter Property="Stylus.IsFlicksEnabled" Value="False"/> 
            <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Border x:Name="BackBorder" SnapsToDevicePixels="true"          Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"  VerticalAlignment="{TemplateBinding VerticalAlignment}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}"  Background="{TemplateBinding Background}" CornerRadius="5"  BorderThickness="{TemplateBinding BorderThickness}" Tag="{TemplateBinding Tag}" BorderBrush="{TemplateBinding BorderBrush}">
                        
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="35"/>
                            </Grid.ColumnDefinitions>
                            <ScrollViewer  Grid.Column="0" x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                            <TextBlock  x:Name="tbWatermark"
                                            Grid.Column="0"
                                            Padding="2,0"
                                            Margin="{TemplateBinding Padding}"
                                            Foreground="{TemplateBinding Foreground}"
                                            FontSize="{TemplateBinding FontSize}"
                                            TextWrapping="Wrap"
                                            Focusable="False"
                                            IsHitTestVisible="False"
                                            Visibility="Collapsed"
                                            Text="{Binding Path=(local:TextBoxHelper.Watermark),RelativeSource={RelativeSource AncestorType=TextBox}, Mode=OneWay}"
                                            VerticalAlignment="Center"
                                            HorizontalAlignment="Left"
                                            Opacity="0.5" />
                        <TextBlock Name="Danwei" Grid.Column="1" Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=TextBox, Mode=FindAncestor}}" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,5,0"/> 
                    </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <DataTrigger Binding="{Binding Text,RelativeSource={RelativeSource Self},Converter={StaticResource IsNullOrEmptyConverter }}"  Value="True">
                            <Setter Property="Visibility" TargetName="tbWatermark" Value="Visible" />
                        </DataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style> 

其中有个需要设定 附件属性的地方就是(本次我们把操作类放在同一个文件夹所以使用Local 就可以找到对应的属性):

csharp 复制代码
  Text="{Binding Path=(local:TextBoxHelper.Watermark),RelativeSource={RelativeSource AncestorType=TextBox}, Mode=OneWay}"

但是因为转换类是在其他方法内,所以此地需要引入操作

csharp 复制代码
  <DataTrigger Binding="{Binding Text,RelativeSource={RelativeSource Self},Converter={StaticResource IsNullOrEmptyConverter }}"  Value="True">

引入的写法和xaml标准方法: 引入地址

csharp 复制代码
xmlns:local1="clr-namespace:海王牌位系统.CommonInMy.Converter">

设定本地读取key

csharp 复制代码
<local1:IsNullOrEmptyConverter x:Key="IsNullOrEmptyConverter"/>

4 应用在界面的xaml下的操作:引入Key

csharp 复制代码
 <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="../CommonInMy/Styles/TextBoxStyle.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

当然也要引用附加属性所在地址:

csharp 复制代码
xmlns:Local1="clr-namespace:海王牌位系统.CommonInMy.Styles"

使用在textbox下的操作:

csharp 复制代码
  <TextBox Name="GetText" Width="200" Tag="Kg" Height="30" Style="{DynamicResource  HelperTextWaterCanEdit}" Local1:TextBoxHelper.Watermark="你觉得好吗" >

            </TextBox>

其中水印 就是附加属性 设定的text ,Tag则单位的显示数据。

效果如下:使用text 读出来的实际就是textbox里的值

使用附加属性操作水印建议推荐先拜读这篇文章

https://blog.csdn.net/qq_39488878/article/details/126251868

使用圆角以及水印加入单位推荐拜读这个

https://cloud.tencent.com/developer/article/1513535

其中原来的样式是粘贴下直接可以使用,确定就是水印不能自己随意修改:

csharp 复制代码
 <SolidColorBrush x:Key="TextBox.Static.Border" Color="#FFABAdB3"/>
    <SolidColorBrush x:Key="TextBox.MouseOver.Border" Color="#FF7EB4EA"/>
    <SolidColorBrush x:Key="TextBox.Focus.Border" Color="#FF569DE5"/>
    <VisualBrush x:Key="HintText" TileMode="None" Opacity="0.5" Stretch="None" AlignmentX="Left">
        <VisualBrush.Visual>
            <TextBlock FontStyle="Italic" Text="请输入数据"/>
        </VisualBrush.Visual>
    </VisualBrush>

    <Style x:Key="TBoxLightWatermarkWithUnit" TargetType="{x:Type TextBox}">
        <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
        <Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border}"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
        <Setter Property="HorizontalContentAlignment" Value="Left"/>
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="AllowDrop" Value="true"/>
        <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
        <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"
                                CornerRadius="2"
                                >
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="35"/>
                            </Grid.ColumnDefinitions>

                            <ScrollViewer Grid.Column="0" x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
                            <TextBlock Grid.Column="1" Text="mm" VerticalAlignment="Center" Margin="0,0,5,0"/>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Opacity" TargetName="border" Value="0.56"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource TextBox.MouseOver.Border}"/>
                        </Trigger>
                        <Trigger Property="IsKeyboardFocused" Value="true">
                            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource TextBox.Focus.Border}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="IsInactiveSelectionHighlightEnabled" Value="true"/>
                    <Condition Property="IsSelectionActive" Value="false"/>
                </MultiTrigger.Conditions>
                <Setter Property="SelectionBrush" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightBrushKey}}"/>
            </MultiTrigger>

            <Trigger Property="Text" Value="{x:Null}">
                <Setter Property="Background" Value="{StaticResource HintText}"/>
            </Trigger>
            <Trigger Property="Text" Value="">
                <Setter Property="Background" Value="{StaticResource HintText}"/>
            </Trigger>

        </Style.Triggers>
    </Style>
相关推荐
小白15 小时前
WPF自定义Dialog模板,内容用不同的Page填充
wpf
Crazy Struggle19 小时前
C# + WPF 音频播放器 界面优雅,体验良好
c#·wpf·音频播放器·本地播放器
James.TCG1 天前
WPF动画
wpf
He BianGu2 天前
笔记:简要介绍WPF中FormattedText是什么,主要有什么功能
笔记·c#·wpf
脚步的影子2 天前
.NET 6.0 + WPF 使用 Prism 框架实现导航
.net·wpf
jyl_sh2 天前
Ribbon (WPF)
ribbon·wpf·client·桌面程序开发·c/s客户端
wo63704312 天前
[Visual Stuidio 2022使用技巧]2.配置及常用快捷键
c#·.net·wpf
小黄人软件2 天前
wpf 字符串 与 变量名或函数名 相互转化:反射
wpf
界面开发小八哥3 天前
DevExpress WPF中文教程:如何解决排序、过滤遇到的常见问题?(二)
.net·wpf·界面控件·devexpress·ui开发
Vae_Mars3 天前
WPF中图片的宫格显示
wpf