【WPF异常】在使用 ItemsSource 之前,项集合必须为空
1 <DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="620" Height="269" AutoGenerateColumns="False" GridLinesVisibility="None" CanUserDeleteRows="False" 2 CanUserAddRows="False" ItemsSource="{Binding ListStudent}"> 3 <DataGridTextColumn Header="编号" Width="80" Binding="{Binding Student.studentid}"/> 4 <DataGridTextColumn Header="姓名" Width="80" Binding="{Binding Student.name}"/> 5 <DataGridTextColumn Header="年龄" Width="80" Binding="{Binding Student.age}"/> 6 <DataGridTextColumn Header="性别" Width="80" Binding="{Binding Student.sex}"/> 7 <DataGridTextColumn Header="特点" Width="120" Binding="{Binding Student.remark}"/> 8 <DataGridTemplateColumn Header="选中" SortMemberPath="IsSelected" Width="120"> 9 <DataGridTemplateColumn.CellTemplate> 10 <DataTemplate> 11 <CheckBox IsChecked="{Binding Path=IsSelected,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" Command="{Binding Path=DataContext.SelectStudentItemCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}" 12 /> 13 </DataTemplate> 14 </DataGridTemplateColumn.CellTemplate> 15 </DataGridTemplateColumn> 16 </DataGrid>
报错“在使用 ItemsSource 之前,项集合必须为空”
观察一下便可发现设计器里没有正确显示各列,是因为少了DataGrid.Columns节点
1 <DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="620" Height="269" AutoGenerateColumns="False" GridLinesVisibility="None" CanUserDeleteRows="False" 2 CanUserAddRows="False" ItemsSource="{Binding ListStudent}"> 3 <DataGrid.Columns> 4 <DataGridTextColumn Header="编号" Width="80" Binding="{Binding Student.studentid}"/> 5 <DataGridTextColumn Header="姓名" Width="80" Binding="{Binding Student.name}"/> 6 <DataGridTextColumn Header="年龄" Width="80" Binding="{Binding Student.age}"/> 7 <DataGridTextColumn Header="性别" Width="80" Binding="{Binding Student.sex}"/> 8 <DataGridTextColumn Header="特点" Width="120" Binding="{Binding Student.remark}"/> 9 <DataGridTemplateColumn Header="选中" SortMemberPath="IsSelected" Width="120"> 10 <DataGridTemplateColumn.CellTemplate> 11 <DataTemplate> 12 <CheckBox IsChecked="{Binding Path=IsSelected,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" Command="{Binding Path=DataContext.SelectStudentItemCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}" 13 /> 14 </DataTemplate> 15 </DataGridTemplateColumn.CellTemplate> 16 </DataGridTemplateColumn> 17 </DataGrid.Columns> 18 </DataGrid>
改为以上即可