本章具体作用:给出一个非依赖属性 需要去使用binding的例子
<StackPanel>
<!--使用附加属性-->
<PasswordBox x:Name="pbox" Password="111"
local:PasswordBoxHelper.IsEnablePasswordPropertyChanged="True"
local:PasswordBoxHelper.Pwd="{Binding MyPasswordVM,Mode=TwoWay}"/>
<TextBox Text="{Binding MyPasswordVM}"/>
<!--使用例子-->
<TextBox Text="{Binding ElementName=pbox,Path=(local:PasswordBoxHelper.Pwd)}"/>
<Button Click="Button_Click" Content="改变"/>
</StackPanel>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
// 依赖属性,是具备自动通知界面的能力
public string MyPasswordVM
{
get { return (string)GetValue(MyPasswordVMProperty); }
set { SetValue(MyPasswordVMProperty, value); }
}
// Using a DependencyProperty as the backing store for MyPasswordVM. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPasswordVMProperty =
DependencyProperty.Register("MyPasswordVM", typeof(string), typeof(MainWindow));
private void Button_Click(object sender, RoutedEventArgs e)
{
MyPasswordVM = DateTime.Now.ToString("HH:mm:ss.ffff");
}
}
创建一个PasswordBoxHelper的类
public class PasswordBoxHelper
{
//创建附加属性 例子grid.row 使用propa
public static string GetPwd(DependencyObject obj)
{
return (string)obj.GetValue(PwdProperty);
}
public static void SetPwd(DependencyObject obj, string value)
{
obj.SetValue(PwdProperty, value);
}
// Using a DependencyProperty as the backing store for Pwd. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PwdProperty =
DependencyProperty.RegisterAttached("Pwd", typeof(string), typeof(PasswordBoxHelper));
//再创建一个附加属性
public static bool GetIsEnablePasswordPropertyChanged(DependencyObject obj)
{
return (bool)obj.GetValue(IsEnablePasswordPropertyChangedProperty);
}
public static void SetIsEnablePasswordPropertyChanged(DependencyObject obj, bool value)
{
obj.SetValue(IsEnablePasswordPropertyChangedProperty, value);
}
//一旦值有改变,就调用这个回调函数
// Using a DependencyProperty as the backing store for IsEnablePasswordPropertyChanged. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsEnablePasswordPropertyChangedProperty =
DependencyProperty.RegisterAttached("IsEnablePasswordPropertyChanged", typeof(bool), typeof(PasswordBoxHelper), new PropertyMetadata(false,OnPasswordPropertyChanged));
private static void OnPasswordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
PasswordBox pwdbox = d as PasswordBox;
// 这步操作是说,如果这个附加属性在PasswordBox里面,就继续走代码
if (pwdbox == null)
return;
if((bool)e.NewValue)
{
pwdbox.PasswordChanged += MyPasswordPropertyChanged;
}
else
{
pwdbox.PasswordChanged -= MyPasswordPropertyChanged;
}
}
private static void MyPasswordPropertyChanged(object sender, RoutedEventArgs e)
{
PasswordBox box = (PasswordBox)sender;
SetPwd(box, box.Password);
}
}