C#从列表中填充列表视图

因此,在我的C#(WPF)应用程序中,我使用表单填充患者列表。 我需要这些患者出现在列表视图中,因为它们已被添加。

public class Patients { public string lastname; public string firstname; public string rm; public int age; public string notes; public int status; public Patients(string lastname, string firstname, int age, string rm, string notes, int status) { this.lastname = lastname; this.firstname = firstname; this.notes = notes; this.status = status; } } public partial class MainWindow : Window { public List newPatientList = new List(); public void AddNewPatient(string lastname, string firstname, int age, string rm, string notes, int status) { newPatientList.Add(new Patients(lastname, firstname, age, rm, notes, status)); } } 

这使得患者对名单很好。

            

我正在尝试将数据绑定到列表,但它不会填充。

只需使用ObservableCollection而不是List

 public ObservableCollection newPatientList = new ObservableCollection(); 

你的控件没有更新的原因是List无法告诉控件它的集合已经改变了,让控件忘记何时更新自己。

ObservableCollection将在其集合发生更改时通知控件,并且将呈现所有项目。

请记住,更改集合中项目的任何属性仍然不会通知控件,但我认为这是该问题的范围之外。

wpf绑定需要属性Patients类声明字段

代替

 public string lastname; 

使

 public string lastname { get;set; } 

根据通用的命名惯例,它应该更好

 public string LastName { get;set; } 

不要忘记修复绑定,它们区分大小写

 "{Binding LastName}" 

你有newPatientList字段的类似问题。

 public List newPatientList = new List(); 

并且不要忘记设置Window DataContext 。 绑定从DataContext中查找值。 如果为null,则不会显示任何值