///2015-5-21注:很多情况下,在构造函数中给ItemsSource赋值会报此错。改到Loaded事件中即可
///2014-9-9注:ItemsControl的模版各有不同。集合有<ItemsControl.ItemTemplate> 、<ItemsControl.Template>;
///注意搭配:
数据集合
<ItemsControl> <ItemsControl.ItemTemplate> <DataTemplate> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>控件集合
<ItemsControl> <ItemsControl.Template> <ControlTemplate> </ControlTemplate> </ItemsControl.Template> </ItemsControl>//
写好了一个简单的WPF窗体,ItemsSource也绑定了一个集合;后台的Loaded事件中也初始化了DataContext;
一切顺理成章。我漫不经心地调试,居然报“在使用 ItemsSource 之前,项集合必须为空”?!!
怎么会?写了这么多遍怎么可能报错?!一怒之下急火攻心,迅速喝了几大杯水,对照以前的代码细究。。。。哎呀,原来如此!
就因为掉了 <ItemsControl.ItemTemplate> !!
<pre name="code" class="html"> <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal">
<TextBlock Text="{Binding TestAttribute.time,NotifyOnSourceUpdated=True}" SourceUpdated="TextBlock_SourceUpdated"/>
<TextBlock Text=" "/>
<TextBlock Text="{Binding TestAttribute.name,NotifyOnSourceUpdated=True}" SourceUpdated="TextBlock_SourceUpdated"/>
<TextBlock Text=" "/>
<TextBlock Text="{Binding TestAttribute.ID,NotifyOnSourceUpdated=True}" SourceUpdated="TextBlock_SourceUpdated"/>
</StackPanel>
<Grid Grid.Row="1">
<ItemsControl ItemsSource="{Binding BindingList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding time}" Grid.Column="0"/>
<TextBlock Text="{Binding name}" Grid.Column="1"/>
<TextBlock Text="{Binding ID}" Grid.Column="2"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Grid>
以此纪念我疯魔那个晚上。。。