WPF我的List <t> </t>有问题

时间:2014-09-01 03:26:58

标签: c# wpf

这是我的功能。

public List<DiseaseSymptomParams> GetSelectedDiseaseSymptom()
{
    var entiParams = new DiseaseSymptomParams();
    var selectedDiseases = new List<DiseaseSymptomParams>();

    try
    {
        foreach (DiseaseSymptom itemSelected in DiseaseSymptomsDataGrid.ItemsSource)
        {
            var cellContent = (CheckBox)StatusIdColumn.GetCellContent(itemSelected);
            if (cellContent != null && cellContent.IsChecked == true)
            {
                entiParams.Id = DefaultValue.GetInt(itemSelected.Id);
                selectedDiseases.Add(entiParams);
            }
        }
    }
    catch (Exception)
    {

    }
    return selectedDiseases;
}

显然,如果我选择2个或更多项目(使用复选框),所有复选框都将添加到selectedDiseases,但最后一个已添加的项目将覆盖列表中的所有条目。

2 个答案:

答案 0 :(得分:6)

您只有entiParams的一份副本,您不断修改并重新添加到列表中。将对象的创建放在循环中,这样你就可以创建新的对象,而不是修改旧的。

foreach (DiseaseSymptom itemSelected in DiseaseSymptomsDataGrid.ItemsSource)
{
    var cellContent = (CheckBox)StatusIdColumn.GetCellContent(itemSelected);
    if (cellContent != null && cellContent.IsChecked == true)
    {
        var entiParams = new DiseaseSymptomParams();
        entiParams.Id = DefaultValue.GetInt(itemSelected.Id);
        selectedDiseases.Add(entiParams);
    }
}

答案 1 :(得分:0)

entiParams是一种引用类型,selectedDiseases列表不断添加相同的实例。这样做:

public List<DiseaseSymptomParams> GetSelectedDiseaseSymptom()
{
    var selectedDiseases = new List<DiseaseSymptomParams>();

    try
    {
        foreach (DiseaseSymptom itemSelected in DiseaseSymptomsDataGrid.ItemsSource)
        {
            var cellContent = (CheckBox)StatusIdColumn.GetCellContent(itemSelected);
            if (cellContent != null && cellContent.IsChecked == true)
            {
                var entiParams = new DiseaseSymptomParams
                {
                    Id = DefaultValue.GetInt(itemSelected.Id)
                };
                selectedDiseases.Add(entiParams);
            }
        }
    }
    catch (Exception)
    {

    }
    return selectedDiseases;
}