【问题标题】:C# Populating a listview from a ListC# 从列表中填充列表视图
【发布时间】:2017-08-09 07:30:30
【问题描述】:

因此,在我的 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>

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

【问题讨论】:

  • 这是因为List&lt;T&gt; 没有通知绑定控件其集合已更改。尝试使用 ObservableCollection&lt;T&gt; 而不是 List&lt;T&gt;
  • ... 和一个 ViewModel 而不是将模型填充到 View 代码中。
  • 离题了,当这个类的一个实例代表一个单个患者时,调用你的类Patients是很奇怪的。我有一个偷偷摸摸的怀疑你使用复数是因为List&lt;Patients&gt;,但你最好使用List&lt;Patient&gt;。尽管在处理列表时听起来不太正确,但在处理类包含在列表中时,使用单数作为类名听起来会更正确。您已经可以在示例中看到它发生了,AddNewPatient()(单数)方法执行以下操作:.Add(new Patients())(复数)

标签: c# wpf


【解决方案1】:

只需使用ObservableCollection 而不是List

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

您的控件未更新的第三个原因是,List 无法告知控件其集合已更改,从而使控件忘记了何时更新自身。

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

请记住,更改集合内项目的任何属性仍然不会通知控件,但我认为这超出了这个问题的范围。

【讨论】:

    【解决方案2】:

    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 中查找值。如果为null,则不会显示任何值

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多