Silverlight 4: ListBoxItem Selection Problem
I need to programatically select a subset of ListBoxItems in a ListBox (SelectedMode=Multiple) control.
<Grid x:Name="LayoutRoot" Background="White">
<ListBox Height="238" HorizontalAlignment="Left" Margin="26,41,0,0" Name="listBox1" VerticalAlignment="Top" Width="349" SelectionMode="Multiple" />
<Button Content="Fill" Height="23" HorizontalAlignment="Left" Margin="26,12,0,0" Name="buttonFill" VerticalAlignment="Top" Width="75" Click="buttonFill_Click" />
<Button Content="Randomly Select" Height="23" HorizontalAlignment="Left" Margin="116,12,0,0" Name="buttonSelectRandom" VerticalAlignment="Top" Width="104" Click="buttonSelectRandoml_Click" />
</Grid>
private void buttonFill_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 100; i++)
listBox1.Items.Add(new ListBoxItem { Content = i.ToString()});
}
private void buttonSelectRandom_Click(object sender, RoutedEventArgs e)
{
var rand = new Random();
foreach (ListBoxItem item in listBox1.Items)
if (rand.Next(2)==1) item.IsSelected = true;
}
However it seems that only the currently visible items show as selected when I run the code (click the "Fill" button and then the "Randomly Select" button). Scrolling through the ListBox shows no other ListBoxItems as selected even though a check of their "IsSelected" 开发者_开发知识库state in code will show them set to "true".
Interestingly, if I manually scroll to the end of the ListBox (or part way) first and then click the "Randomly Select" button then the ListBox will draw all the selected items correctly . I have tried many workarounds but can't seem to find one that works. Is this a bug? Any workarounds?
Thanks for your help.
Jink
this might be because the ListBox's using VirtualizingStackPanel. Can you test it with a normal StackPanel?
<ListBox>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
Edit:
Another solution is, instead of doing item.IsSelected = true, you do
foreach (int item in listBox1.Items)
{
if (rand.Next(2) == 1)
{
this.listBox1.SelectedItems.Add(item);
}
}
I have tested it and it works. :)
精彩评论