Wpf的Binding

发布于:2025-06-26 ⋅ 阅读:(14) ⋅ 点赞:(0)

前言

wpf的Binding就像一个桥梁,它的作用就是连接逻辑层与界面层,既能够把逻辑层的数据搬到界面层展示,又能将界面层的数据更改后传递到逻辑层,Binding的数据来源就是Binding的源,数据展示的地方就是Binding的目标。

1、新建一个类

下面的代码中新建了一个Student类,该类有一个简单的属性Name, 并且该类实现了INotifyPropertyChanged接口,实现该接口的目的是当Name属性的Set方法被触发以后通过PropertyChanged事件就能通知Binding,Name属性值已发生更改,从而通知Binding的目标更新界面,该类的对象可以作为Binding的源。

   class Student: INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string name;
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
                if(this.PropertyChanged !=null)
                {
                    PropertyChanged.Invoke(this,new PropertyChangedEventArgs("Name"));
                }
            }
        }
    }

2、准备界面

容器StackPanel中放了一个Button一个TextBox,并且给Button注册了一个事件btn_Test_Click,每次点击Button就会把Student类的对象的Name值+10,这个对象就是Binding的源,这样就相当于利用Button去改变Binding源的值。

<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <Button x:Name="btn_Test"  Height="20" Click="btn_Test_Click"/>
        <TextBox x:Name="tbx_test"  Height="20"/>
    </StackPanel>
</Window>
  private void btn_Test_Click(object sender, RoutedEventArgs e)
        {
            student.Name += "10";
        }

3、准备数据源、Binding、简历源和目标的连接

下面代码中首先通过new一个Student类的对象建立了一个Binding源;然后声明一个Binding类的对象,指定Binding对象源是student对象,并且指定Binding的Path也就是源中的属性是Name(对应student的Name属性);最后使用BindingOperations.SetBinding方法建立源和目标之间的关联,该方法第一个参数是目标对象,这里对应tbx_test,第二个参数是目标的属性,这里是对应 TextBox属性,第三个参数是Binding对象,这样就建立了源(Student的Name属性)、目标(tbx_test的Text属性)

  Student student;
        public MainWindow()
        {
            InitializeComponent();
            student = new Student();//准备数据源


            Binding binding = new Binding();//声明Binding对象
            binding.Source = student;//指定Binding的源
            binding.Path = new PropertyPath("Name"); //指定Binding的路径,也就是源的哪个属性


            BindingOperations.SetBinding(this.tbx_test, TextBox.TextProperty, binding);//分别指定Binding的目标对象、目标对象的哪个属性,Binding对象
            //tbx_test.SetBinding(TextBox.TextProperty ,new Binding ("Name"){ Source=student });
        }

4、运行结果

点击一次按钮,tbx_test就会增加“10”
在这里插入图片描述

马工撰写的年入30万+C#上位机项目实战必备教程(点击下方链接即可访问文章目录)

1、《C#串口通信从入门到精通》
2、《C#与PLC通信从入门到精通 》
3、《C# Modbus通信从入门到精通》
4、《C#Socket通信从入门到精通 》
5、《C# MES通信从入门到精通》
6、《winform控件从入门到精通》
7、《C#操作MySql数据库从入门到精通》


网站公告

今日签到

点亮在社区的每一天
去签到