对如何通过WPF来创建一个listBox,并同后台数据链接,实现数据驱动实施更新UI界面,做一个简单的样例介绍。(简陋的UI和一塌糊涂的命名还请大家见谅)
首先现在XAML中创建UI如下图。
在CS中先定义一个employee类继承于INotifyPropertyChanged接口,当这个类的实例发生变化的时候会给binding发送一个通知,数据在UI上显示即发生变化。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Annotations;
namespace listBox
{
//创建一个Employee的类
public class Employee : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string name;
public int id { get; set; }
public string Name
{
get { return name; }
set
{ name = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
}
public int age { get; set; }
}
}
创建一个包含多个employee对象的ObservableCollection<>。再把ObservableCollection赋予给listBox且对要显示的对象属性进行一个声明。注意此处一定要使用ObservableCollection而非List,ObservableCollection实现了INotifyCollectionChanged接口,集合一旦发生变化就会通知UI更新。
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 listBox
{
///
/// MainWindow.xaml 的交互逻辑
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.listBoxEmployee.SelectedValuePath = "id";
把list和listBox做一个连接
//this.listBoxEmployee.ItemsSource = employees;
DisplayMemberPath告诉listBox应该显示list中每个对象的哪个属性
//this.listBoxEmployee.DisplayMemberPath = "Name";
//this.listBoxEmployee.ItemsSource = employees;
Binding binding = new Binding() { Source = employees};
this.listBoxEmployee.SetBinding(ListBox.ItemsSourceProperty, binding);
}
ObservableCollection employees = new ObservableCollection()
{
new Employee(){id = 11,Name = "aaaa",age = 21 },
new Employee(){id = 2,Name = "bbb",age = 22 },
new Employee(){id = 3,Name = "ccc",age = 23 },
new Employee(){id = 4,Name = "ddd",age = 24 },
new Employee(){id = 5,Name = "eeee",age = 25 },
new Employee(){id = 6,Name = "ffff",age = 26 },
new Employee(){id = 7,Name = "gggg",age = 27 },
new Employee(){id = 8,Name = "hhh",age = 28 },
new Employee(){id = 9,Name = "iii",age = 29 },
new Employee(){id = 10,Name = "jjjj",age = 30 }
};
private void Button_Click(object sender, RoutedEventArgs e)
{
string idText = this.STUid.Text;
int ID = Convert.ToInt32(idText);
string name = this.STUname.Text;
string ageText = this.STUage.Text;
int age = Convert.ToInt32(ageText);
Employee employee = new Employee() { age = age, Name = name, id = ID };
employees.Add(employee);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string name = this.STUname.Text;
employees[1].Name = name;
}
}
}



