《深入浅出WPF》学习笔记(二)——Binding

本文深入探讨WPF中的Binding,讲解了Binding的源与路径,包括如何为Binding指定Source,如CLR对象、集合、ADO.NET数据对象、XML数据等。并给出了用控件属性、DataContext及集合作为Binding源的实例,展示了数据驱动UI的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Binding

Binding模型
如果Binding比作数据的桥梁,那么它的两端分别是Binding的源(Source)和目标(Target)。源是数据的来源,目标是数据的去处。一般情况下,Binding的源是逻辑层对象,目标是UI层的控件对象,逻辑层数据通过Binding源源不断地送达UI层,被UI层展现,完成了数据驱动的过程。

一、Binding的源和路径

  • Binding的源:对象;
  • Binding的路径:UI元素所关心的对象的某一属性;
  • 接口:让作为数据源的类实现System.ComponentModel命名空间中的INotifyPropertyChangeed接口,并在属性的set语句中激发PropertyChanged事件。

实现了接口的类如下:

class Test : INotifyPropertyChanged
{
   
   
    public event PropertyChangedEventHandler PropertyChanged;
    private string name;
    public string Name //Name属性
    {
   
   
        get {
   
    return name; }
        set
        {
   
   
            name = value;
            //激发事件
            if (this.PropertyChanged != null)
            {
   
   
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
            }
        }
    }
}
为Binding指定源(Source)的几种方法:
  • CLR类型单个对象:包括 .NET Framework自带类型的对象和用户自定类型的对象;
  • CLR集合类型的对象:包括数组、List<>、ObservableCollection<>等集合类型;
  • ADO.NET数据对象:包括DataTable和DateView等对象;
  • 使用XmlDataProvider指定XML数据;
  • 依赖对象;
  • DataContext;
  • 使用Element指定等。

二、Binding对象(实例)

以代码为例:

public partial class Window1:Window
{
   
   
	Test test;
	public Window1()
	{
   
   
		InitializeComponent();
		//准备数据源
		test = new Test();
	
		//准备Binding
		Binding binding = new Binding();//声明
		binding.Source = test;//指定Binding源
		binding.Path = new PropertyPath("Name");//指定Binding的路径
	
		//使用Binding连接数据源与Binding目标
		BindingOperations.SetBinding(this.textBox,TextBox.TextProperty,bingding);
	}
	//...
}

BindingOperations.SetBinding()方法完成了将数据源和目标连接在一起的重要任务:

BindingOperations.SetBinding(DependencyObject target, 
                DependencyProperty dp, BindingBase binding);
            /* DependencyObject target:指定Binding的目标;
             * DependencyProperty dp:指明把数据送到目标的哪个属性(与数据源的Path类似);
             * BindingBase:使用哪个Binding实例进行绑定
            */

也可以对上述代码进行简化:

this.textBox.SetBinding(TextBox.TextProperty
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值