开发者

Virtualizing Stack Panel Returning Null Selected Item

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 Is开发者_开发问答Selected}" 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?


Maybe you can define a FallBackValue inside your Binding, to get back the FallBackValue instead of null.


My best guess would be that your selected item is null when it is out of view in the listbox.

It makes sense I guess because of the virtualization though it is an odd one.

Your solution is likely to be that when your selected item changes you make sure you bring it in to view. Take a look at this question to sort that out.

Good luck & HTH

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜