2017-08-09 117 views
0

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

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<Patients> newPatientList = new List<Patients>(); 

    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)); 
    } 
} 

这增加了病人的名单。

<ListView ItemsSource="{Binding newPatientList}" x:Name="listView" HorizontalAlignment="Stretch" Margin="0,0,0,0" SelectionChanged="listView_SelectionChanged"> 
     <ListView.View> 
      <GridView> 
       <GridViewColumn Header="RM #" DisplayMemberBinding="{Binding rm}"/> 
       <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding lastname}"/> 
       <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding firstname}"/> 
       <GridViewColumn Header="Status" DisplayMemberBinding="{Binding status}"/> 
      </GridView> 
     </ListView.View> 
    </ListView> 

我试图将数据绑定到列表,但它不填充。

+1

这是因为'List '不会通知绑定控件它的集合已经改变。尝试使用'ObservableCollection '而不是'List ' –

+0

...和ViewModel,而不是将模型填充到视图代码中。 – Fildor

+1

Offtopic,当这个班级的一个实例代表一个_single_患者时,调用你的班级“患者”是非常奇怪的。我有一个鬼鬼祟祟的嫌疑,你已经使用了复数,因为'List ',但你最好使用'List '。尽管在处理列表时,听起来不那么正确,但在处理类时,使用单数作为类名听起来会更加正确 - 当它不是列在list_中时。你已经可以看到它发生在你的例子中,方法'AddNewPatient()'(奇异)会执行以下操作:'.Add(new Patients())'(复数) – Flater

回答

1

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

代替

public string lastname; 

使

public string lastname { get;set; } 

也根据命名规范,它最好是

public string LastName { get;set; } 

不要忘了修复绑定,他们区分大小写

"{Binding LastName}" 

你有newPatientList场类似的问题。

public List<Patients> newPatientList = new List<Patients>(); 

并且不要忘记设置窗口DataContext。绑定从DataContext查找值。如果是空,不会有任何显示值

2

只需使用的ObservableCollection代替List的:

public ObservableCollection<Patients> newPatientList = new ObservableCollection<Patients>(); 

THRE原因,你的控制没有更新,是List说不出的控制,其集合已经发生了变化,导致控制无视何时更新自身。

ObservableCollection将在控件集合发生变化时通知控件,并且所有项目都将呈现。请记住,更改集合内的项目的任何属性仍然不会通知控件,但我认为这是这个问题的范围的ouside。