Binding

1新建wpf程序

2 新建Student类

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp9
{
    public class Student:INotifyPropertyChanged
    {
        private string _Name = "";
        public string Name
        {
            get { return _Name; }

            set
            {
                _Name = value;
                OnPropertyChanged("Name");
            }

        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

 3.修改ui


    
        
            
            
        
    

4 主程序

using System;
using System.Collections.Generic;
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 WpfApp9
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        Student student;
        public MainWindow()
        {
            InitializeComponent();

            student = new Student();

            //Binding binding = new Binding();
            //binding.Source = student;
            //binding.Path = new PropertyPath("Name");

            //BindingOperations.SetBinding(this.textBoxName, TextBox.TextProperty, binding);

            //可以简写成下面的样子
            this.textBoxName.SetBinding(TextBox.TextProperty,new Binding("Name"){ Source=student});
        }

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

 

你可能感兴趣的:(WPF)