Reputation: 127
So in my C# (WPF) application I use a form to populate a list of patients. I need these patients to show up in a listview, as they're added.
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));
}
}
This adds patients fine to the list.
<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>
I'm trying to bind the data to the list, but it does not populate.
Upvotes: 0
Views: 1602
Reputation: 8643
Simply use an ObservableCollection
instead of List
:
public ObservableCollection<Patients> newPatientList = new ObservableCollection<Patients>();
Thre reason your control is not updating, is that List
cannot tell the control that its collection has changed, leaving the control oblivious of when to update itself.
ObservableCollection
will notify the control whenever its collection changes, and all items will be rendered.
Keep in mind, that changing any property of the items inside the collection still will not notify the control, but i think that is ouside the scope of this question.
Upvotes: 2
Reputation: 35680
wpf bindings require properties. Patients
class declares fields.
instead of
public string lastname;
make
public string lastname { get;set; }
also according to common naming convention it should better be
public string LastName { get;set; }
don't forget to fix bindings, they are case-sensitive
"{Binding LastName}"
you have similar issue with newPatientList
field.
public List<Patients> newPatientList = new List<Patients>();
and don't forget to set Window DataContext
. Bindings look up values from DataContext. if it is null, there won't be any values displayed
Upvotes: 1