依赖属性:解决不能绑定的控件属性 如下图示例
使用依赖属性让控件的属性Password 能绑定
1创建依赖属性 快捷键 propa
2 修改一下快捷创建的依赖属性
public static int GetPassword(DependencyObject obj)
{
return (int)obj.GetValue(Password);
}
public static void SetPassword(DependencyObject obj, string value)
{
obj.SetValue(Password, value);
}
// Using a DependencyProperty as the backing store for Password. This enables animation, styling, binding, etc...
public static readonly DependencyProperty Password =
DependencyProperty.RegisterAttached("Password", typeof(string), typeof(MainWindow), new PropertyMetadata(null,new PropertyChangedCallback((e, s) =>
{
var passwordBox = (e as PasswordBox);
passwordBox.Password = s.NewValue.ToString();
})));//一个属性回调 将设置的附加属性值与 password 属性关联
3 在控件上使用依赖属性
<Window
x:Class="依赖属性.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:依赖属性"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Grid>
<PasswordBox local:MainWindow.Password="测试" />
<!-- Password 属性不能绑定 非依赖属性
想让Password 能绑定
1要添加附加属性
2将附加属性与Password 属性关联起来 -->
<!--<Button Content="" />-->
<!-- Content依赖属性可以绑定 -->
</Grid>
</Window>
4 运行效果:
图例解释:成功赋值给Password