I was using a stack panel to display listbox items, but when I decided to change it to a virtualizing one the selected item was null sometimes. Here is part of the DataTemplate I was using to invoke the selected item command:
<i:Interaction.Triggers>
<ei:DataTrigger Binding="{Binding IsSelected}" Value="True">
<i:InvokeCommandAction CommandParameter="{Binding}"
Command="{Binding DataContext.SelectItemCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}, Mode=FindAncestor}}" />
</ei:DataTrigger>
</i:Interaction.Triggers>
Here is the ListBox:
<ListBox x:Name="_itemsListBox"
Grid.Row="1"
ScrollViewer.CanContentScroll="true"
ItemsSource="{Binding Items}"
IsSynchronizedWithCurrentItem="True"
SelectionMode="Single"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ItemTemplate="{StaticResource ListItemTemplate}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
If I turn off virtualization, this issue doesn't happen. How can I prevent it from returning a null item?