wpf的binding学习记录

今天看一个同事写的代码,发现他的binding写的不是很规范,但是仍把前后台数据绑了起来,很是奇怪,自己写了几行代码做了下测试,记录如下。

首先先新建一个Student类,包含id和name两个字段。(注释的行是正常写法)

 public class Student
        //: INotifyPropertyChanged
    {
        //public event PropertyChangedEventHandler PropertyChanged;

        //public void NotifyPropertyChanged(string propertyName)
        //{
        //    if (PropertyChanged != null)
        //    {
        //        PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        //    }
        //}
        string id;
        public string Id
        {
            get { return id; }
            set { id = value;
            //NotifyPropertyChanged("Id");
            }
        }
        string name;
        public string Name
        {
            get { return name; }
            set { name = value;
            //NotifyPropertyChanged("Name");
            }
        }        
    }
新建一个mainWindow

前台代码


    
        
            
            
            
        
        
            
            
            
        
        
        
        


后台代码

public partial class MainWindow : Window     
    {       
        public Student student = new Student();
        public Student Student
        {
            get { return student; }
            set {
                student = value;           
            }
            
        }
        public MainWindow()
        {
            student.Id = "init1";
            InitializeComponent();
            student.Id = "init";
         
        }
        private void buttonA_Click(object sender, RoutedEventArgs e)
        {
            student.Id = textid.Text;
            student.Name = textname.Text;
            Console.WriteLine(Student.Id+Student.Name);
        }
    }

执行程序,发现虽然Student里面并没有加入继承INotifyPropertyChanged接口,但是界面上textid1仍然会显示init1. 修改text1的值,发现后台student.id值也相应变化了。

但是修改textid的值,利用button传到后台,并不会引起textid1的变化,类似于binding里面的mode.onewaytosource。

并且如果student的初始值放 在InitializeComponent的后面,并不会引起前台的变化。具体的机制还有待研究。

虽然这种方式,能满足简单的数据binding需求,并且写法简单,但还是应该把代码写完善,否则对于像我这种二把刀会造成很大的困惑。


你可能感兴趣的:(wpf)