[英]C# Populating a listview from a List
因此,在我的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<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>
我正在嘗試將數據綁定到列表,但不會填充。
只需使用ObservableCollection
而不是List
:
public ObservableCollection<Patients> newPatientList = new ObservableCollection<Patients>();
因此,您的控件未更新的原因是List
無法告知控件其集合已更改,從而使控件不知道何時進行更新。
每當控件的集合更改時, ObservableCollection
都會通知該控件,並且所有項目都將呈現。
請記住,更改集合內項目的任何屬性仍不會通知控件,但我認為這是該問題的范圍。
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>();
並且不要忘記設置Window DataContext
。 綁定從DataContext查找值。 如果為空,則不會顯示任何值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.