Skip to main content

WPF ItemsControl and Operation is not valid while ItemsSource is in use…

Greg Roberts

Greg Roberts

Greg Roberts

See anything wrong with the following XAML:

<ItemsControl ItemsSource="{Binding GridColumns}" Grid.Row="1" Grid.Column="0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Margin="0,14" Height="22" >
<TextBlock TextAlignment="Center" Text="{Binding Name}"></TextBlock>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Clicked">
<n:ExecuteCommandAction Command="{Binding HighlightColumn}" Parameter="{Binding Index}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" >
</StackPanel>
</ItemsPanelTemplate>
</ItemsControl>

Yeah I didn’t see it initially either, but if you run this you will get an error indicating that you are trying to modify the source collection. Look closely at the ItemsPanelTemplate, while the syntax is correct it needs to be wrapped in ItemsControl.ItemsPanel. Since it isn’t it treats that statement as an item and tries to add it to the collection. The corrected Xaml is as follows:

<ItemsControl ItemsSource="{Binding GridColumns}" Grid.Row="1" Grid.Column="0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Margin="0,14" Height="22" >
<TextBlock TextAlignment="Center" Text="{Binding Name}"></TextBlock>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Clicked">
<n:ExecuteCommandAction Command="{Binding HighlightColumn}" Parameter="{Binding Index}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>