标签:present 快速 div 语言 register mic back get width
Windows Presentation Foundation(WPF)提供了一组服务,这些服务可用于扩展公共语言运行时(CLR)属性的功能,这些服务通常统称为WPF属性系统。由WPF属性系统支持的属性称为依赖项属性(Dependency Property)。
基本上依赖属性都支持绑定(Binding),但也并不是说,非依赖属性就不能使用绑定。例如我们常用的密码框(PasswordBox)为了保证安全性,它的Password属性就不是依赖属性(即不能以Binding的方式实现数据通知),但是我们可以通过附加属性、行为的方式实现绑定。
首先,我们创建一个名为PasswordBoxHelper的类,为Password注册附加属性。
1 public class PasswordBoxHelper 2 { 3 public static string GetPassword(DependencyObject obj) 4 { 5 return (string)obj.GetValue(PasswordProperty); 6 } 7 8 public static void SetPassword(DependencyObject obj, string value) 9 { 10 obj.SetValue(PasswordProperty, value); 11 } 12 13 // Using a DependencyProperty as the backing store for Password. This enables animation, styling, binding, etc... 14 public static readonly DependencyProperty PasswordProperty = 15 DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordBoxHelper), new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged)); 16 17 private static void OnPasswordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 18 { 19 PasswordBox passwordBox = d as PasswordBox; 20 string password = (string)e.NewValue; 21 22 if (passwordBox != null && !string.Equals(passwordBox.Password, password)) 23 { 24 passwordBox.Password = password; 25 } 26 } 27 }
然后,在创建一个名为PasswordBoxBehavior的类,继承自Behavior,为PasswordBox附加行为。
1 public class PasswordBoxBehavior : Behavior<PasswordBox> 2 { 3 protected override void OnAttached() 4 { 5 base.OnAttached(); 6 AssociatedObject.PasswordChanged += AssociatedObject_PasswordChanged; 7 } 8 9 protected override void OnDetaching() 10 { 11 base.OnDetaching(); 12 AssociatedObject.PasswordChanged -= AssociatedObject_PasswordChanged; 13 } 14 15 private void AssociatedObject_PasswordChanged(object sender, RoutedEventArgs e) 16 { 17 PasswordBox passwordBox = sender as PasswordBox; 18 19 string password = PasswordBoxHelper.GetPassword(passwordBox); 20 21 if (passwordBox != null && passwordBox.Password != password) 22 { 23 PasswordBoxHelper.SetPassword(passwordBox, passwordBox.Password); 24 } 25 } 26 }
最后,在界面上为我们在PasswordBoxHelper类中注册的Password设置属性绑定,同时为PasswordBox设置Behavior。
1 <PasswordBox x:Name="txtPwd" Width="180" VerticalContentAlignment="Center" Background="Transparent" MaxLength="8"
helper:PasswordBoxHelper.Password="{Binding Path=Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> 2 <i:Interaction.Behaviors> 3 <helper:PasswordBoxBehavior /> 4 </i:Interaction.Behaviors> 5 </PasswordBox>
以上就完成了密码框的属性绑定。
Tips:
在“工具-选项-常规-键盘”中选择Visual C# 2005。
在代码中输入“propa”,再按tab键可以快速生成注册附加属性的代码。生成的代码如下图:
在代码中输入“propdp”,再按tab键可以快速生成注册依赖属性的代码。生成的代码如下图:
标签:present 快速 div 语言 register mic back get width
原文地址:https://www.cnblogs.com/writecode/p/11919316.html