首页 > 代码库 > 【WPF异常】在使用 ItemsSource 之前,项集合必须为空
【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>
改为以上即可
【WPF异常】在使用 ItemsSource 之前,项集合必须为空
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。