WPF数据绑定、多个元素

1.前台代码

<Window x:Class="WorkingWithTemplates.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="250" Width="300">
    <Grid Name="grid">
        <TextBox Height="20" Text="{Binding Path=Name}"  HorizontalAlignment="Left" Margin="63,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="139" />
        <TextBox Height="20"  Text="{Binding Path=Age}"  HorizontalAlignment="Left" Margin="63,48,0,0" Name="textBox2" VerticalAlignment="Top" Width="139" />
        <Button Content="显示用户信息" Height="26" HorizontalAlignment="Left" Margin="60,118,0,0" Name="button1" VerticalAlignment="Top" Width="144" Click="button1_Click" />
        <Button Content="修改用户信息" Height="26" HorizontalAlignment="Left" Margin="60,158,0,0" Name="button2" VerticalAlignment="Top" Width="144" Click="button2_Click" />
    </Grid>
</Window>

2.后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.ComponentModel;

namespace WorkingWithTemplates
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private Person p1 = new Person();
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            grid.DataContext = p1;//绑定数据
            p1.Name = "李四";
        }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            p1.Age = p1.Age + 1;
            p1.Name += "1";
        }
    }
    public class Person : INotifyPropertyChanged
    {
        private String _name = "张三";
        private int _age = 24;

        public String Name
        {
            set{
                _name = value;
                if (PropertyChanged != null){
                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));//对Name进行监听
                }
            }
            get{
                return _name;
            }
        }

        public int Age
        {
            set{
                _age = value;
                if (PropertyChanged != null){
                    PropertyChanged(this, new PropertyChangedEventArgs("Age"));//对Age进行监听
                }
            }
            get{return _age;}
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

单片机,嵌入式LINUX技术交流群:142282597
原文地址:https://www.cnblogs.com/qiujiahong/p/3118279.html