WPF 依赖属性

依赖属性:解决不能绑定的控件属性 如下图示例

使用依赖属性让控件的属性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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学软件开发的猪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值