WPF依赖属性

依赖属性是一种可以自己没有值,并能通过使用Binding从数据源获取值(依赖在别人身上)的属性。
优点:

  • 节省实例对内存的开销。
  • 属性值可以通过Binding依赖在其他对象身上。

WPF的所有控件都是依赖属性。

依赖对象被DependencyObject类实现,依赖属性由DependencyProperty类实现。
DependencyObject有GetValue()、SetValue()。
GetValue():通过DependencyProperty对象获取数据。
SetValue():通过DependencyProperty对象存储值。

public object GetValue(){DependencyProperty dp}
public void setValue(DependencyProperty dp, object value){}

propdp + Tab + tab 声明依赖属性 ,继续 Tab+Tab可以修改依赖属性的各个参数。

public static readonly DependencyProperty NameProperty =
       DependencyProperty.Register("Name", //属性名称
       typeof(string), //属性类型
       typeof(Student), //该属性所有者,即将该属性注册到那个类上
       new PropertyMetadata("")); //属性默认值

eg:

public class Student:DependencyObject{
    //CLR属性包装器
    public string Name{
        get{return (string)GetValue(NameProperty);}
        set{SetValue(NameProperty, value);}
    }

    //依赖属性
    public static readonly DependencyProperty NameProperty = 
            DependencyPropertyRegister("Name", typeof(string), typeof(Student));

    //SetBinding包装
    public BindingExpressionBase SetBinding(DependencyProperty dp, 
            BindingBase binding){
        return BindingOperations.SetBinding(this, dp, binding);
    }
}

public class Window1{
    //使用Binding把Student对象关联到textBox1上,再把textBox2关联到Student对象上形成Binding链。
    public Window1(){
        InitializeComponent();
        stu = new Student();
        stu.SetBinding(Student.NameProperty, new Binding("Text"){Source = textBox1});
        textBox2.SetBinding(TextBox.TextProperty, new Binding("Name"){Source = stu});
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值