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>
相关推荐
月落.9 小时前
WPF的<ContentControl>控件
wpf
就是有点傻9 小时前
WPF中的依赖属性
开发语言·wpf
wangnaisheng9 小时前
【WPF】把一个Window放在左上角/右上角顶格显示
wpf
WineMonk9 小时前
.NET WPF CommunityToolkit.Mvvm框架
.net·wpf·mvvm
月落.9 小时前
WPF中的INotifyPropertyChanged接口
wpf
界面开发小八哥9 小时前
界面控件DevExpress WPF中文教程:Data Grid——卡片视图设置
.net·wpf·界面控件·devexpress·ui开发
平凡シンプル9 小时前
WPF 打包
wpf
VickyJames9 小时前
基于XAML框架和跨平台项目架构设计的深入技术分析
wpf·开源分享·unoplatform·winui3·项目架构
冷眼Σ(-᷅_-᷄๑)12 小时前
WPF缩放动画和平移动画叠加后会发生什么?
wpf·动画
△曉風殘月〆15 小时前
WPF MVVM入门系列教程(二、依赖属性)
c#·wpf·mvvm