• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

C# Wpf自定义控件实现密码框(PasswordBox)明密文切换、清除功能和数据绑定(二)

武飞扬头像
morliz子轩
帮助12

一、自定义控件封装

Windows Presentation Foundation (WPF) 提供了一组服务,这些服务可用于扩展公共语言运行时 (CLR) 属性的功能,这些服务通常统称为 WPF 属性系统。由 WPF 属性系统支持的属性称为依赖项属性。

1、依赖属性DependencyProperty

(1) 依赖属性原型

  1.  
    /* 将其他类型添加为已注册的依赖对象所有者,从而为依赖属性提供依赖属性元数据使其存在于提供的所有者类型上。
  2.  
    * ownerType: 要作为此依赖属性所有者添加的类型。
  3.  
    * typeMetadata: 在依赖属性存在于所提供的类型上时对其进行限定的元数据。
  4.  
    */
  5.  
    public DependencyProperty AddOwner(Type ownerType);
  6.  
    public DependencyProperty AddOwner(Type ownerType, PropertyMetadata typeMetadata);
  7.  
     
  8.  
    /* 表示可通过诸如样式、数据绑定、动画和继承等方法设置的属性。
  9.  
    * 方法描述: 使用指定的属性名称、属性类型、所有者类型、属性元数据和属性的值验证回叫来注册依赖属性。
  10.  
    * name: 属性名称
  11.  
    * propertyType: 属性类型
  12.  
    * typeMetadata: 依赖属性的属性元数据
  13.  
    * validateValueCallback: 对回调的引用,除了典型的类型验证之外,该引用还应执行依赖属性值的任何自定义验证。
  14.  
    */
  15.  
    public static DependencyProperty Register(string name, Type propertyType, Type ownerType);
  16.  
     
  17.  
    public static DependencyProperty Register(string name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata);
  18.  
     
  19.  
    public static DependencyProperty Register (string name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata, ValidateValueCallback validateValueCallback);
  20.  
     
  21.  
     
  22.  
    /* 在抽象类上注册附加属性。 此附加属性是枚举类型属性,注册会添加验证回调,以验证所提供的值是否为枚举值。
  23.  
    * 方法描述: 使用指定的属性类型、所有者类型、属性元数据和属性的值验证回调来注册附加属性。
  24.  
    * name: 属性名称
  25.  
    * propertyType: 属性类型
  26.  
    * typeMetadata: 依赖属性的属性元数据。 这可以包括默认值和其他特征。
  27.  
    * validateValueCallback: 对回调的引用,除了典型的类型验证之外,该引用还应执行依赖属性值的任何自定义验证。
  28.  
    */
  29.  
    public static DependencyProperty RegisterAttached(string name, Type propertyType, Type ownerType);
  30.  
     
  31.  
    public static DependencyProperty RegisterAttached(string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata);
  32.  
     
  33.  
    public static DependencyProperty RegisterAttached(string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata, ValidateValueCallback validateValueCallback);
  34.  
    /* 官方注解
  35.  
    * 附加属性是由可扩展应用程序标记语言定义的属性概念, (XAML) 。 WPF 将附加属性作为依赖项属性实现。 由于 WPF 附加属性是依赖属性,因此它们可以应用元数据,常规属性系统可以使用这些元数据来实现报表布局特征等操作。
  36.  
    */
  37.  
     
  38.  
    /* 为此依赖属性(当它位于指定的对象实例上时)返回元数据。
  39.  
    * dependencyObjectType: 一个特定对象,该对象记录需要其中的依赖属性元数据的依赖项对象类型。
  40.  
    * forType: 要从中检索依赖属性元数据的特定类型。
  41.  
    * dependencyObject: 一个依赖对象,检查了其类型,以便确定元数据应来自依赖属性的哪个类型特定版本。
  42.  
    */
  43.  
    public PropertyMetadata GetMetadata(DependencyObjectType dependencyObjectType);
  44.  
    public PropertyMetadata GetMetadata(Type forType);
  45.  
    public PropertyMetadata GetMetadata(DependencyObject dependencyObject);
  46.  
     
学新通

这里笔者仅提取了几处常用的依赖属性的使用方法,详请类方法请见:DependencyProperty 类 (System.Windows) | Microsoft Learn

(2) 自定义控件资源

  1.  
    <!-- 定义CheckBox 预置属性及模板相关样式 -->
  2.  
    <Style TargetType="CheckBox" x:Key="CheckBoxStyle">
  3.  
    <Setter Property="FontFamily" Value="../Assets/Fonts/#iconfont"></Setter>
  4.  
    <Setter Property="HorizontalAlignment" Value="Right"></Setter>
  5.  
    <Setter Property="VerticalAlignment" Value="Center"></Setter>
  6.  
    <Setter Property="Margin" Value="0 0 5 0"></Setter>
  7.  
    <Setter Property="Template">
  8.  
    <Setter.Value>
  9.  
    <ControlTemplate TargetType="CheckBox">
  10.  
    <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=Content}"
  11.  
    Margin="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=Margin}" />
  12.  
    </ControlTemplate>
  13.  
    </Setter.Value>
  14.  
    </Setter>
  15.  
     
  16.  
    </Style>
学新通

注意,此处FontFamily属性是通过 IconFont字体图标动态进行加载,具体实现方式请参考:

在WPF中使用iconfont-爱码网

(3) 密码框属性样式

a. TextBox可见样式

  1.  
    <!-- 定义密码框使用的TextBox 预置属性可见样式 -->
  2.  
    <Style TargetType="TextBox" x:Key="PasswordVisibleStyle">
  3.  
    <Setter Property="FontWeight" Value="Regular"></Setter>
  4.  
    <Setter Property="FocusVisualStyle" Value="{x:Null}" />
  5.  
    <Setter Property="Foreground" Value="#303133"></Setter>
  6.  
    <Setter Property="Template">
  7.  
    <Setter.Value>
  8.  
    <ControlTemplate TargetType="TextBox">
  9.  
    <Border BorderBrush="#dcdfe6" CornerRadius="4" BorderThickness="1"
  10.  
    Background="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=Background}">
  11.  
    <Grid>
  12.  
    <Grid.ColumnDefinitions>
  13.  
    <ColumnDefinition></ColumnDefinition>
  14.  
    <ColumnDefinition Width="Auto"></ColumnDefinition>
  15.  
    <ColumnDefinition Width="Auto"></ColumnDefinition>
  16.  
    </Grid.ColumnDefinitions>
  17.  
     
  18.  
    <ScrollViewer x:Name="PART_ContentHost" BorderThickness="0" VerticalAlignment="Center"
  19.  
    FontSize="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path= FontSize}" IsTabStop="False" Margin="2"
  20.  
    Background="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path= Background}" />
  21.  
    <!-- 清空内容 -->
  22.  
    <CheckBox Grid.Column="1" Style="{StaticResource CheckBoxStyle}" Content="&#xe60a;" Foreground="#e6e6e6"
  23.  
    IsChecked="{Binding (local:CustPasswordBox.IsCleared),
  24.  
    RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Mode=TwoWay}"
  25.  
    Visibility ="{Binding (local:CustPasswordBox.ClearVisibility),
  26.  
    RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Mode=TwoWay}" />
  27.  
     
  28.  
    <!-- 显示内容 -->
  29.  
    <CheckBox Grid.Column="2" Style="{StaticResource CheckBoxStyle}" Content="&#xe60d;" Foreground="#bfbfbf"
  30.  
    IsChecked="{Binding (local:CustPasswordBox.IsChecked),
  31.  
    RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Mode=TwoWay}" />
  32.  
    </Grid>
  33.  
    </Border>
  34.  
    </ControlTemplate>
  35.  
    </Setter.Value>
  36.  
    </Setter>
  37.  
    </Style>
学新通

b. TextBox隐藏样式

  1.  
    <!-- 定义密码框使用的TextBox 预置属性隐藏样式 -->
  2.  
    <Style TargetType="PasswordBox" x:Key="PasswordBoxCollapsedStyle">
  3.  
    <Setter Property="FontWeight" Value="Regular" />
  4.  
    <Setter Property="FocusVisualStyle" Value="{x:Null}" />
  5.  
    <Setter Property="Foreground" Value="#303133" />
  6.  
    <Setter Property="Template">
  7.  
    <Setter.Value>
  8.  
    <ControlTemplate TargetType="PasswordBox">
  9.  
    <Border BorderBrush="#dcdfe6" CornerRadius="4" BorderThickness="1"
  10.  
    Background="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=Background}">
  11.  
    <Grid>
  12.  
    <Grid.ColumnDefinitions>
  13.  
    <ColumnDefinition></ColumnDefinition>
  14.  
    <ColumnDefinition Width="Auto"></ColumnDefinition>
  15.  
    <ColumnDefinition Width="Auto"></ColumnDefinition>
  16.  
    </Grid.ColumnDefinitions>
  17.  
     
  18.  
    <ScrollViewer x:Name="PART_ContentHost" BorderThickness="0" VerticalAlignment="Center"
  19.  
    FontSize="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=FontSize}"
  20.  
    IsTabStop="False" Margin="2"
  21.  
    Background="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=Background}" />
  22.  
    <!-- 清空内容 -->
  23.  
    <CheckBox Grid.Column="1" Style="{StaticResource CheckBoxStyle}" Content="&#xe60a;" Foreground="#e6e6e6"
  24.  
    IsChecked="{Binding (local:CustPasswordBox.IsCleared),
  25.  
    RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Mode=TwoWay}"
  26.  
    Visibility ="{Binding (local:CustPasswordBox.ClearVisibility),
  27.  
    RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Mode=TwoWay}"/>
  28.  
     
  29.  
    <!-- 隐藏内容 -->
  30.  
    <CheckBox Grid.Column="2" Style="{StaticResource CheckBoxStyle}" Content="&#xe60c;" Foreground="#bfbfbf"
  31.  
    IsChecked="{Binding (local:CustPasswordBox.IsChecked),
  32.  
    RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Mode=TwoWay}"/>
  33.  
     
  34.  
    </Grid>
  35.  
    </Border>
  36.  
    <ControlTemplate.Triggers>
  37.  
    <Trigger Property="IsEnabled" Value="false">
  38.  
    <Setter Property="Background" Value="#ebeef5"></Setter>
  39.  
    </Trigger>
  40.  
    </ControlTemplate.Triggers>
  41.  
    </ControlTemplate>
  42.  
    </Setter.Value>
  43.  
    </Setter>
  44.  
    </Style>
学新通

c. PasswordBox封装

  1.  
    <Grid>
  2.  
    <TextBox Style="{StaticResource PasswordVisibleStyle}"
  3.  
    Visibility="{Binding (local:CustPasswordBox.TBoxVisibility),RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Mode=TwoWay}"
  4.  
    Text="{Binding (local:CustPasswordBox.Password),RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox>
  5.  
     
  6.  
    <PasswordBox Style="{StaticResource PasswordBoxCollapsedStyle}"
  7.  
    Visibility="{Binding (local:CustPasswordBox.PwdVisibility),RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Mode=TwoWay}"
  8.  
    local:PasswordBoxHelper.Attach="True" local:PasswordBoxHelper.Password="{Binding (local:CustPasswordBox.Password),
  9.  
    RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}},Mode=TwoWay,
  10.  
    UpdateSourceTrigger=PropertyChanged}">
  11.  
     
  12.  
    </PasswordBox>
  13.  
    </Grid>

 此处,传递的相关属性如下:

  • ScrollViewer.Background属性,Border及ScrollViewer对象有受该属性影响;
  • ScrollViewer.FontSize属性
  • CheckBox.IsChecked属性:引用CustPasswordBox.IsCleared依赖
  • CheckBox.Visibility属性:引用CustPasswordBox.ClearVisibility依赖
  • TextBox.Visibility属性:引用CustPasswordBox.TBoxVisibility依赖
  • TextBox.Text属性:引用CustPasswordBox.Password依赖
  • PasswordBox.Visibility属性:引用CustPasswordBox.PwdVisibility依赖

附加属性绑定:

  • PasswordBoxHelper.Attach属性
  • PasswordBoxHelper.Password属性:引用CustPasswordBox.Password依赖

(4) 依赖属性定义

  1.  
    /// <summary>
  2.  
    /// CustPasswordBox.xaml 的交互逻辑
  3.  
    /// </summary>
  4.  
    public partial class CustPasswordBox : UserControl
  5.  
    {
  6.  
    public CustPasswordBox()
  7.  
    {
  8.  
    InitializeComponent();
  9.  
    }
  10.  
     
  11.  
    /// <summary>
  12.  
    /// 清除显示属性
  13.  
    /// </summary>
  14.  
    public static readonly DependencyProperty ClearVisibilityProperty = DependencyProperty.Register(
  15.  
    "ClearVisibility", typeof(Visibility), typeof(CustPasswordBox), new PropertyMetadata(Visibility.Collapsed));
  16.  
     
  17.  
    /// <summary>
  18.  
    /// 叉叉图标状态(隐藏/隐藏)字段
  19.  
    /// </summary>
  20.  
    public Visibility ClearVisibility
  21.  
    {
  22.  
    get => (Visibility)GetValue(ClearVisibilityProperty);
  23.  
    set => SetValue(ClearVisibilityProperty, value);
  24.  
    }
  25.  
     
  26.  
    /// <summary>
  27.  
    /// 密码属性
  28.  
    /// </summary>
  29.  
    public static readonly DependencyProperty PasswordProperty = DependencyProperty.Register(
  30.  
    "Password", typeof(string), typeof(CustPasswordBox), new PropertyMetadata((s, e) =>
  31.  
    {
  32.  
    var sender = s as CustPasswordBox;
  33.  
     
  34.  
    //根据密码框是否有内容来显示叉叉图标
  35.  
    sender.ClearVisibility = !string.IsNullOrEmpty(sender.Password) ? Visibility.Visible : Visibility.Collapsed;
  36.  
     
  37.  
    }));
  38.  
     
  39.  
    /// <summary>
  40.  
    /// 密码字段
  41.  
    /// </summary>
  42.  
    public string Password
  43.  
    {
  44.  
    get => (string)GetValue(PasswordProperty);
  45.  
    set => SetValue(PasswordProperty, value);
  46.  
    }
  47.  
     
  48.  
    /// <summary>
  49.  
    /// 清空元数据的事件属性
  50.  
    /// </summary>
  51.  
    public static readonly DependencyProperty IsClearedProperty = DependencyProperty.Register(
  52.  
    "IsCleared", typeof(bool), typeof(CustPasswordBox), new PropertyMetadata((s, e) =>
  53.  
    {
  54.  
    var sender = s as CustPasswordBox;
  55.  
    sender.Password = "";
  56.  
    }));
  57.  
     
  58.  
    /// <summary>
  59.  
    /// 清空元数据字段
  60.  
    /// </summary>
  61.  
    public bool IsCleared
  62.  
    {
  63.  
    get => (bool)GetValue(IsClearedProperty);
  64.  
    set => SetValue(IsClearedProperty, value);
  65.  
    }
  66.  
     
  67.  
    /// <summary>
  68.  
    /// TBoxVisibility明文属性
  69.  
    /// </summary>
  70.  
    public static readonly DependencyProperty TBoxVisibilityProperty = DependencyProperty.Register(
  71.  
    "TBoxVisibility", typeof(Visibility), typeof(CustPasswordBox));
  72.  
     
  73.  
    /// <summary>
  74.  
    /// 显示或隐藏明文字段
  75.  
    /// </summary>
  76.  
    public Visibility TBoxVisibility
  77.  
    {
  78.  
    get => (Visibility)GetValue(TBoxVisibilityProperty);
  79.  
    set => SetValue(TBoxVisibilityProperty, value);
  80.  
    }
  81.  
     
  82.  
    /// <summary>
  83.  
    /// 密文属性
  84.  
    /// </summary>
  85.  
    public static readonly DependencyProperty PwdVisibilityProperty = DependencyProperty.Register(
  86.  
    "PwdVisibility", typeof(Visibility), typeof(CustPasswordBox));
  87.  
     
  88.  
    /// <summary>
  89.  
    /// 显示或隐藏密文字段
  90.  
    /// </summary>
  91.  
    public Visibility PwdVisibility
  92.  
    {
  93.  
    get => (Visibility)GetValue(PwdVisibilityProperty);
  94.  
    set => SetValue(PwdVisibilityProperty, value);
  95.  
    }
  96.  
     
  97.  
     
  98.  
    /// <summary>
  99.  
    /// IsChecked事件属性
  100.  
    /// </summary>
  101.  
    public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register(
  102.  
    "IsChecked", typeof(bool), typeof(CustPasswordBox), new PropertyMetadata((s, e) =>
  103.  
    {
  104.  
    var cpb = s as CustPasswordBox;
  105.  
    if ((bool)e.NewValue)
  106.  
    {
  107.  
    //Ischecked为True时
  108.  
    cpb.TBoxVisibility = Visibility.Visible;
  109.  
    cpb.PwdVisibility = Visibility.Collapsed;
  110.  
    }
  111.  
    else
  112.  
    {
  113.  
    //Ischecked为False时
  114.  
    cpb.TBoxVisibility = Visibility.Collapsed;
  115.  
    cpb.PwdVisibility = Visibility.Visible;
  116.  
    }
  117.  
    }));
  118.  
     
  119.  
    /// <summary>
  120.  
    /// IsChecked字段
  121.  
    /// </summary>
  122.  
    public bool IsChecked
  123.  
    {
  124.  
    get => (bool)GetValue(IsCheckedProperty);
  125.  
    set => SetValue(IsCheckedProperty, value);
  126.  
    }
  127.  
    }
学新通

 二、UserControl控件调用

1、DataContext数据源配置

  1.  
    /// <summary>
  2.  
    /// MainWindow.xaml 的交互逻辑
  3.  
    /// </summary>
  4.  
    public partial class MainWindow : Window
  5.  
    {
  6.  
    private readonly PasswordBoxViewModel PwdViewModel;
  7.  
     
  8.  
    public MainWindow()
  9.  
    {
  10.  
    InitializeComponent();
  11.  
    PwdViewModel = new PasswordBoxViewModel();
  12.  
    DataContext = PwdViewModel;
  13.  
    }
  14.  
    }
  15.  
     
  16.  
    /// <summary>
  17.  
    /// 密码框模型
  18.  
    /// </summary>
  19.  
    public class PasswordBoxViewModel : INotifyPropertyChanged
  20.  
    {
  21.  
    public event PropertyChangedEventHandler PropertyChanged;
  22.  
     
  23.  
    public void RaisePropertyChanged([CallerMemberName] string propertyName = null)
  24.  
    {
  25.  
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  26.  
    }
  27.  
     
  28.  
    private string _password;
  29.  
    public string Password
  30.  
    {
  31.  
    get => _password;
  32.  
    set
  33.  
    {
  34.  
    _password = value;
  35.  
    RaisePropertyChanged();
  36.  
    }
  37.  
    }
  38.  
    }
学新通

2. XAML前端调用

  1.  
    <Window xmlns:BaseUI="clr-namespace:WpfAppDemo.BaseUI"
  2.  
    x:Class="WpfAppDemo.MainWindow"
  3.  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4.  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5.  
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  6.  
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  7.  
    xmlns:local="clr-namespace:WpfAppDemo"
  8.  
    d:DataContext="{d:DesignInstance Type=local:PasswordBoxViewModel}"
  9.  
    mc:Ignorable="d"
  10.  
    WindowStyle="None" WindowStartupLocation="CenterScreen"
  11.  
    AllowsTransparency="True" Background="Transparent"
  12.  
    Title="MainWindow" Height="200" Width="350" >
  13.  
     
  14.  
    <Border BorderBrush="#20333333" BorderThickness="1" CornerRadius="8" Background="White" Margin="0">
  15.  
    <Border.Effect>
  16.  
    <DropShadowEffect BlurRadius="8" Color="#20333333" ShadowDepth="0"></DropShadowEffect>
  17.  
    </Border.Effect>
  18.  
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
  19.  
    <TextBlock Text="自定义密码框:" VerticalAlignment="Center"></TextBlock>
  20.  
    <BaseUI:CustPasswordBox Password="{Binding Password,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
  21.  
    Height="24" Width="200"></BaseUI:CustPasswordBox>
  22.  
    </StackPanel>
  23.  
    </Border>
  24.  
    </Window>
学新通

挑重点,其中BaseUI:CustPasswordBox需xmlns:BaseUI="clr-namespace:WpfAppDemo.BaseUI"作为引用条件,d:DataContext="{d:DesignInstance Type=local:PasswordBoxViewModel}"则为数据源前端绑定,可自动生成。

控件效果:

学新通

--END--

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfckgij
系列文章
更多 icon
同类精品
更多 icon
继续加载