// Class1.cs using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks;
namespaceWpfApp1 { //继承INotifyPropertyChanged类 classClass1 : INotifyPropertyChanged { //实现PropertyChanged接口 publicevent PropertyChangedEventHandler? PropertyChanged; string name; publicstring Name { get { returnthis.name; } set { name = value; //当属性变更时激发事件 if(this.PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name")); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks;
namespaceWpfApp1 { classClass1 : INotifyPropertyChanged { string name; publicstring Name { get { return name; } set { name = value; if(this.PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name")); } } } int age; publicint Age { get { return age; } set { age = value; if (this.PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Age")); } } } string phonetype; publicstring Phonetype { get { return phonetype; } set { phonetype = value; if (this.PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Phonetype")); }
} }
int id; publicint ID { get { return id; } set { id = value; if (this.PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs("ID")); } } }
ObservableCollection< Class1 > olist = new ObservableCollection<Class1>() { new Class1 { Name = "小明",Phonetype="小米 13",ID=1,Age=14 }, new Class1 { Name = "小花",Phonetype="华为 mate 60 pro",ID=2,Age=24 }, new Class1 { Name = "小华",Phonetype="魅族 10",ID=3,Age=16 }, new Class1 { Name = "小军",Phonetype="一加 8",ID=4,Age=19 }, new Class1 { Name = "小俊",Phonetype="荣耀 11",ID=5,Age=10 }, new Class1 { Name = "小胡",Phonetype="苹果 14",ID=6,Age=12 }, new Class1 { Name = "小虎",Phonetype="OPPO A8",ID=7,Age=25 }, new Class1 { Name = "小帅",Phonetype="Vivo X100",ID=8,Age=32 }, new Class1 { Name = "小美",Phonetype="IQOO Neo 9",ID=9,Age=17 }, new Class1 { Name = "小壮",Phonetype="小辣椒 1",ID=10,Age=16 }, new Class1 { Name = "小丽",Phonetype="诺基亚 8",ID=11,Age=22 }, new Class1 { Name = "李华",Phonetype="OPPO A5",ID=12,Age=43 }, }; //设置源和路径 this.ID_ListBox.ItemsSource = olist; this.ID_ListBox.DisplayMemberPath = "Name"; //将TextBox与被选中的Items的ID绑定 Binding binding = new Binding("SelectedItem.ID") { Source=this.ID_ListBox}; this.ID_TextBox.SetBinding(TextBox.TextProperty,binding);