从列表中填充列表视图

从列表中填充列表视图

本文介绍了C# 从列表中填充列表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在我的 C# (WPF) 应用程序中,我使用一个表单来填充患者列表.我需要这些患者在添加时显示在列表视图中.

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.

推荐答案

只需使用 ObservableCollection 而不是 List :

Simply use an ObservableCollection instead of List :

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

您的控件未更新的三个原因是 List 无法告诉控件其集合已更改,从而使控件不知道何时更新自身.

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 将在其集合更改时通知控件,并且所有项目都将被呈现.

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.

这篇关于C# 从列表中填充列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 00:27