2010-08-06 55 views
6

與ItemsControl的工作我試圖創造相當大的TextBlocks的滾動列表。我想在那裏有一個垂直滾動條來顯示它們,如果它們溢出一定的大小,我希望它們顯示一個省略號。實際上我所有的工作都很好。獲取UI虛擬化在Silverlight

我有以下的Silverlight XAML:

<Grid x:Name="LayoutRoot" MaxWidth="500" MinWidth="100" 
    MaxHeight="500" MinHeight="100"> 
    <Grid.DataContext> 
     <app:MainPageViewModel/> 
    </Grid.DataContext> 
    <ScrollViewer> 
    <ItemsControl ItemsSource="{Binding TextItems}" Margin="0,20,0,20"> 
     <ItemsControl.ItemTemplate><DataTemplate> 
      <Border MaxHeight="175" Margin="0,0,0,18" CornerRadius="5"> 
       <TextBlock Margin="2" TextTrimming="WordEllipsis" 
        TextWrapping="Wrap" Text="{Binding}"/> 
      </Border> 
     </DataTemplate></ItemsControl.ItemTemplate> 
    </ItemsControl> 
    </ScrollViewer> 
</Grid> 

我的問題是,這種佈局不使用虛擬化的用戶界面,例如用VirtualizingStackPanel。所以它很慢。將UI虛擬化引入此佈局的最佳方式是什麼?我嘗試了大約六種不同的方式,沒有什麼能解決所有問題。

我設法得到這個工作在ListBox,因爲它似乎支持虛擬化的開箱。但是,我更喜歡使用ItemsControl,因爲我不希望這些東西是可選的,我不想要與ListBox一起出現的樣式。

這在Silverlight 4

回答

15

有你需要做的,使這項工作的幾件事情。

  1. 設置ItemsPanelTemplate爲 您的ItemsControl到 VirtualizingStackPanel。
  2. 將的ScrollViewer集成到 的ControlTemplate中,而不是僅將 包裹在外面。
  3. 確保ItemsControl中有一個固定的高度,使佈局系統可以計算出需要多少個項目,填補了視口。 (看起來你已經通過將ItemsControl放置在一個網格中來做到這一點 - 這將允許佈局系統確定控件的分配高度)

這是最簡單的例子,我可以想出這個工作:

<ItemsControl ItemsSource="{Binding TextItems}"> 
     <ItemsControl.ItemsPanel> 
      <ItemsPanelTemplate> 
       <VirtualizingStackPanel /> 
      </ItemsPanelTemplate> 
     </ItemsControl.ItemsPanel> 
     <ItemsControl.Template> 
      <ControlTemplate TargetType="ItemsControl"> 
       <Border> 
        <ScrollViewer> 
         <ItemsPresenter/> 
        </ScrollViewer> 
       </Border> 
      </ControlTemplate> 
     </ItemsControl.Template> 
    </ItemsControl> 
+0

這就像一個魅力史蒂夫。所以,你的解決方案,我試圖做的主要區別是,你用ItemsControl.Template在ScrollViewer中添加,而我只是想放的ScrollViewer上的控制之外。你能解釋爲什麼你的工作原理以及我試圖做的不是嗎?這可能會幫助我更好地理解解決方案。 – RationalGeek 2010-08-08 18:56:40

+1

太棒了,很高興它爲你工作。基本上會發生的是,如果您將一個ScrollViewer放在ItemsControl的外部,那麼佈局引擎將呈現整個ItemsControl - 它將爲控件中的所有項目生成項容器。 ScrollViewer只是將視圖限制到ItemsControl的一小部分,但是具有所有項目的整個ItemsControl都存在於內存中。第二種方法,把ScrollViewer中的模板中給出的ItemsControl限制它創建項目的集裝箱數量的能力 - 這隻會造成足以填滿可用空間。 – 2010-08-08 19:38:05

+0

有道理。再次感謝! – RationalGeek 2010-08-08 23:55:02