WPF实现简单的数据绑定

创建数据源类

首先创建一个作为数据源来使用,这里创建的类需要实现System.ComponentModel名称空间中的INotifyPropertyChanged接口。当为Binding设置了数据源之后,Binding就会自动侦听来自这个接口的PropertyChanged事件。

 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"));
                }
            }
        }
    }

UI

<Window x:Class="WpfApplication1.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:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBox x:Name="textBoxName" BorderBrush="Black" Margin="5"/>
        <Button Content="Change" Margin="5" Click="Button_Click"/>
    </StackPanel>
</Window>

在这里插入图片描述
使用这个界面的目的就是演示,当点击按钮后修改类中的值,UI会不会发生变化

数据源和UI元素连接

public partial class MainWindow : Window
    {
        Student stu;
        public MainWindow()
        {
            InitializeComponent();
            //1----------------------------------------
            //准备数据源
            stu = new WpfApplication1.Student();
            //准备Binding
            Binding binding = new Binding();
            binding.Source = stu;
            binding.Path = new PropertyPath("Name");
            //使用Binding连接数据源与Binding目标
            BindingOperations.SetBinding(this.textBoxName, TextBox.TextProperty, binding);
            //2----------------------------------------
            this.textBoxName.SetBinding(TextBox.TextProperty, new Binding("Name")
            {
                Source = stu = new WpfApplication1.Student()
            });
        }

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

BindingOperations.SetBinding三个参数
第一个参数用于指定Binding目标
第二个参数用于Binding指明把数据送达目标的哪个属性
第三个参数指定使用那个Binding实例将数据源与目标关联起来

猜你喜欢

转载自blog.csdn.net/Maybe_ch/article/details/86165817