封装:WPF中可以绑定的BindPassWord控件

原文:封装:WPF中可以绑定的BindPassWord控件

一、目的:本身自带的PassWord不支持绑定

 

二、Xaml部分

  1. <UserControl x:Class="HeBianGu.General.WpfControlLib.BindPassWordBox"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  5. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  6. xmlns:local="clr-namespace:HeBianGu.General.WpfControlLib"
  7. mc:Ignorable="d"
  8. d:DesignHeight="50" d:DesignWidth="300">
  9. <Grid>
  10. <PasswordBox x:Name="pb_center" PasswordChanged="pb_center_PasswordChanged" />
  11. </Grid>
  12. </UserControl>

三、代码部分

  1. /// <summary> 可以绑定的密码框 </summary>
  2. public partial class BindPassWordBox : UserControl
  3. {
  4. PasswordBox _password = null;
  5. private void pb_center_PasswordChanged(object sender, RoutedEventArgs e)
  6. {
  7. this.PassWord = this._password.Password;
  8. }
  9. public BindPassWordBox()
  10. {
  11. InitializeComponent();
  12. }
  13. public string PassWord
  14. {
  15. get { return (string)GetValue(PassWordProperty); }
  16. set { SetValue(PassWordProperty, value); }
  17. }
  18. // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
  19. public static readonly DependencyProperty PassWordProperty =
  20. DependencyProperty.Register("PassWord", typeof(string), typeof(BindPassWordBox), new PropertyMetadata(default(string), (d, e) =>
  21. {
  22. BindPassWordBox control = d as BindPassWordBox;
  23. if (control == null) return;
  24. string config = e.NewValue as string;
  25. if (control._password == null) return;
  26. control._password.Password = config;
  27. SetPasswordBoxSelection(control._password, config.Length, 0);
  28. }));
  29. private static void SetPasswordBoxSelection(PasswordBox passwordBox, int start, int length)
  30. {
  31. var select = passwordBox.GetType().GetMethod("Select",
  32. BindingFlags.Instance | BindingFlags.NonPublic);
  33. select.Invoke(passwordBox, new object[] { start, length });
  34. }
  35. }

四、原理

封装一层PassWordBox控件,自定义依赖属性,在PassWordBox的Changed事件中赋值依赖属性

 

SetPasswordBoxSelection(control._password, config.Length, 0);

此方法用来设置光标,否则输入后光标位置不正确

封装:WPF中可以绑定的BindPassWord控件

上一篇:Web API design


下一篇:封装:Windows系统文件图标