WPF基础-属性

依赖属性

属性依赖是一个WPF的新概念,即属性本身没有值,通过binding依赖到其他对象身上。

面向对象的设计思路是这样的:人类和人可以当作对象的抽象类和具体实例。当面对人类这个概念时,出生率,死亡率和自然增长率这些属性才有用,而吃饭,喝水还有跑步就显得不合适。而个体人这一实例不适用出生率这些属性,却适合吃喝跑步这些属性。
所以有些属性只对类适用,有些属性更适合实例。
设计上,我们把适合类的属性用设置为静态属性,把适合实例的属性设为非静态属性。因为类只有一个,它的属性也不需要多个,就如人类只有一个出生率。人有很多个,每个人吃的方式可能都不同,所以每新建一个实例,它的属性都需要创建。
但是如果某一场景需要创建无数个实例,这个实例包含众多属性。如果需要为每个属性开辟一个内存控件,那系统进程会受很大影响,所以WPF就有了依赖属性这一概念。

代码实现是这样,先创建一个类,并继承抽象类DependencyObject

	public class Student : DependencyObject
    {
    	//在公共空间内注册一个属性
        public static readonly DependencyProperty NameProperty = 
            DependencyProperty.Register("Name",typeof(string), typeof(Student));
        
    }

这是前端的标签

	<StackPanel>
        <TextBox x:Name="tb1" BorderBrush="Black" Margin="5" />
        <TextBox x:Name="tb2" BorderBrush="Black" Margin="5" />
        <Button Content="OK" Margin="5" Click="Button_Click" />
    </StackPanel>

这是点击事件的实现,第二行代码是关键,把tb1的Text属性值set到student的NameProperty上,形成依赖。

		private void Button_Click(object sender, RoutedEventArgs e)
        {
            Student student = new Student();
            student.SetValue(Student.NameProperty,this.tb1.Text);
            this.tb2.Text = (string)student.GetValue(Student.NameProperty);
        }

运行后点击OK就能把tb1的数据通过实例绑到tb2
在这里插入图片描述
这样的写法还比较原始,当属性依赖和binding同时使用时要多写很多代码,所以写法可以改造一下

改造后写法

类里面这样改造

		public static readonly DependencyProperty NameProperty = 
            DependencyProperty.Register("Name",typeof(string), typeof(Student));
        //这样就可以用传统的点语法调用了
        public string Name { 
            get { return (string)GetValue(Student.NameProperty); }
            set { SetValue(Student.NameProperty,value); }
        }
        //SetBinding包装
        public BindingExpressionBase SetBinding(DependencyProperty dp,BindingBase binding)
        {
            return BindingOperations.SetBinding(this, dp, binding);
        }

构造器中这样调用

		Student student = null;
        public MainWindow()
        {
            InitializeComponent();
            student = new Student();
            student.SetBinding(Student.NameProperty, new Binding("Text") { Source = this.tb1 });
            tb2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = student });
        }

这样就将binding一起绑定了,不需要button,修改tb1直接同步tb2
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值