所以我有使用数据网格的 WPF 应用程序。Datagrid 绑定到自定义类型项的 BindingList。但是当我向列表中添加新项目时,我得到以下 wxception:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
XAML:
<Window x:Class="DoctorApp3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"
Closed="Window_Closed">
<DataGrid AutoGenerateColumns="True"
Height="184" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="dataGrid1" VerticalAlignment="Top" Width="479"
ItemsSource="{Binding}" />
窗口代码:
public BindingList<Patient> tableData;
public List<CompositeType> ntfList;
Listener listener;
public MainWindow()
{
InitializeComponent();
tableData = new BindingList<Patient>()
{
};
//Bind the DataGrid to the customer data
dataGrid1.DataContext= tableData;
dataGrid1.AutoGeneratedColumns += (a, b) =>
{
try
{
dataGrid1.Columns.RemoveAt(0); //the place where exception appears
}
catch (Exception ex)
{
}
dataGrid1.Columns.RemoveAt(1);
dataGrid1.Columns.RemoveAt(2);
};
ntfList = new List<CompositeType>();
dataGrid1.MouseDoubleClick += (a, b) => OpenPatientWindow();
button1.Click += (a, b) => OpenPatientWindow();
}
添加新数据的地方:
public void OnMessageAdded(CompositeType message)
{
if (((message as CompositeType).formTitle.Equals("Informing Doctor")) || ((message as CompositeType).formTitle.Equals("Informing about end therapy")))
{
Patient p = (message as CompositeType).patient;
// (mainWindow as MainWindow).dataGrid1.
(mainWindow as MainWindow).tableData.Add(p);
(mainWindow as MainWindow).ntfList.Add(message as CompositeType);
(mainWindow as MainWindow).dataGrid1.Items.Refresh();
}
}
我通过回调函数 OnMessageAdded 从 WCF 服务获取列表的新数据,但我从服务收到的数据完全没问题。
我使用的自定义类:
[Serializable]
public class Patient
{
[DataMember]
public String PatientId;
[DataMember]
public String Surname;
[DataMember]
public String Name;
[DataMember]
public String Patronymic;
[DataMember]
public String Adress;
[DataMember]
public String Phone;
[DataMember]
public String Birthday;
[DataMember]
public String Diagnosis;
[DataMember]
public String State;
[DataMember]
public String TherapyStart;
[DataMember]
public String TherapyEnd;
}
任何想法为什么它不起作用?
编辑:我在一个类似的项目中,患者对象以下一种方式查看:
在我的项目中,它更像是:
我认为这是一个问题,但不知道这是什么意思。