2011-04-21 65 views
0

我需要以編程方式選擇列表框中的ListBoxItems的一個子集(SelectedMode =多個)控件。Silverlight 4:ListBoxItem選擇問題

<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; 
    } 

但是似乎只有當前可見的項目顯示作爲選擇,當我運行的代碼(單擊「填充」按鈕,然後在「隨機選擇」按鈕)。滾動瀏覽列表框顯示即使在代碼中檢查其「IsSelected」狀態將顯示它們設置爲「true」,也不會選中其他ListBoxItems。有趣的是,如果我首先手動滾動到ListBox(或部分路徑)的末尾,然後單擊「隨機選擇」按鈕,則ListBox將正確繪製所有選定的項目。我嘗試了很多解決方法,但似乎無法找到可行的解決方案。這是一個錯誤?任何解決方法?

感謝您的幫助。

Jink

回答

3

這可能是因爲ListBox使用了VirtualizingStackPanel。你能用一個正常的StackPanel來測試它嗎?

<ListBox> 
     <ListBox.ItemsPanel> 
      <ItemsPanelTemplate> 
       <StackPanel/> 
      </ItemsPanelTemplate> 
     </ListBox.ItemsPanel> 
    </ListBox> 

編輯:

另一種方案是,而不是做item.IsSelected = TRUE,你做

 foreach (int item in listBox1.Items) 
     { 
      if (rand.Next(2) == 1) 
      { 
       this.listBox1.SelectedItems.Add(item); 
      } 
     } 

我已經測試它和它的作品。 :)

+0

+1這對我有效。它還解釋了爲什麼在設置選項之前滾動列表導致項目正確顯示。 – Kimberly 2011-04-21 04:07:37

+0

謝謝,你能接受答案嗎? :) – 2011-04-21 04:09:48

+0

@Xin,我不能接受答案,因爲這不是我的問題。 :)我碰到它,因爲從你的回答中不清楚你自己是否嘗試過這些代碼,但它確實可以解決這個特定問題。無論如何,如果OP由於內存密集型項目而實際需要虛擬化項目面板,我希望他們將這個問題留出幾天,讓很多人有機會與其他可能的解決方法進行權衡。 – Kimberly 2011-04-21 16:44:07