WPF Binding初探

WPF Binding初探

Binding基础

Binding翻译过来就是绑定的意思,WPF中可以把Binding理解成一种连通数据源(Source)和目标(Target)的桥梁。一般情况下,Binding的数据源是逻辑层的对象,Binding目标是UI层的控件对象,这样数据就会源源不断通过Binding送达UI层,在UI层展现出来。

有关Binding的简单例子

以下这个例子创建一个简单的数据源并通过Binding把它连接到UI元素上。

创建一个名为Student的类,这个类的实例作为数据源来使用。

        public class Student
        {
            private string name;
            public string Name
            {
                get { return name; }
                set { name = value; }
            }
        }

这个类只有一个属性,但是一般一个类不止一个属性,到底哪个数据是我们想通过Binding送达UI元素的呢?这个属性就称为Binding的路径(Path)

但是现在光确定了属性还不行,Binding是一种自动机制,当属性值发生了变化之后,要有能力通知Binding,让Binding把变化传递给UI元素。

如何让属性具备这种通知Binding值已经变化的能力呢?

方法是在属性的set语句中激发一个PropertyChanged事件

这个事件不需要我们自己声明,我们要做的只是实现System.ComponentModel名称空间中的INotifyPropertyChanged接口,当为Binding设置了数据源后,Binding就会自动监听来自这个接口的PropertyChanged事件。

实现了INotifyPropertyChanged接口的Student类如下所示:

        public class Student : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            private string name;
            public string Name
            {
                get { return name; }
                set 
                { 
                  name = value; 

                  //激发事件
                  if(this.PropertyChanged != null)
                    {
                        this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
                    }
                }
            }
        }

经过这样升级之后,当Name属性的值发生变化时PropertyChanged事件就会被激发,Binding就会接收到这个事件,于是就会通知Binding目标端的UI元素显示新的值。

代码展示

Xaml代码如下所示:

<Window x:Class="WPFBinding初探.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFBinding初探"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <TextBlock x:Name="textBlock"/>
            <Border Width="50">
                <Button Content="点击" Click="Button_Click"/>
            </Border>
        </StackPanel>
    </Grid>
</Window>

C#代码如下所示:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFBinding初探
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public class Student : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            private string name;
            public string Name
            {
                get { return name; }
                set 
                { 
                  name = value; 

                  //激发事件
                  if(this.PropertyChanged != null)
                    {
                        this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
                    }
                }
            }
        }     
        public MainWindow()
        {
            InitializeComponent();

            //准备数据源
            Student stu = new Student();
            stu.Name = "小王";

            //准备Binding
            Binding binding = new Binding();
            binding.Source = stu;
            binding.Path = new PropertyPath("Name");

            //使用Binding连接数据源与Binding目标
            BindingOperations.SetBinding(this.textBlock,TextBlock.TextProperty, binding);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            stu.Name += "小明";
        }
    }
}

现在来解释一下这段代码,Student stu = new Student();创建了一个Student对象,stu.Name = “小王”;设置这个对象的Name属性为小王, Binding binding = new Binding();创建了一个Binding对象,binding.Source = stu;指定这个binding对象的数据源为stu,binding.Path = new PropertyPath(“Name”);为binding对象指定访问路径为数据源stu的Name属性。

BindingOperations.SetBinding(this.textBlock,TextBlock.TextProperty, binding);将数据源和目标UI元素连在一起。其中第一个参数用于指定Binding的目标,本例中是this.textBlock,第二个参数用于为Binding指明把数据送达目标的哪个属性。这里用的不是对象的属性而是类的一个静态只读(static readonly)DependencyProperty类型成员变量,第三个参数用于指定使用哪个Binding对象实例将数据源与目标关联起来。

Button_Click()方法让我们每点击一次button按钮,stu对象的Name值就会发生改变。

运行结果

程序刚开始的运行结果所下图所示:
在这里插入图片描述

点击之后的效果如下gif图所示:

在这里插入图片描述

其中以下部分代码可以改写:

            //准备Binding
            Binding binding = new Binding();
            binding.Source = stu;
            binding.Path = new PropertyPath("Name");

            //使用Binding连接数据源与Binding目标
            BindingOperations.SetBinding(this.textBlock,TextBlock.TextProperty, binding);

可以将上面这些代码进行改写,如下所示:

this.textBlock.SetBinding(TextBlock.TextProperty, new Binding("Name") { Source = stu });

实现的效果不变

Binding的模型图所下所示:

在这里插入图片描述

参考资料:

《深入浅出WPF》——刘铁锰

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值