2010-01-08 310 views
102

我跟着this關於如何向ItemsControl添加滾動條的小教程,它在Designer視圖中工作,但不是當我編譯和執行程序時(只有前幾項顯示出來,並且沒有滾動條可以查看更多 - 即使VerticalScrollbarVisibility設置爲「可見」而不是「自動」時)。WPF:使用滾動條的ItemsControl(滾動查看器)

關於如何解決這個問題的任何想法?


這是我用它來顯示我的物品(一般我用數據綁定工作,但看到我設計的項目我手動添加它們)的代碼:

<ItemsControl x:Name="itemCtrl" Style="{DynamicResource UsersControlStyle}"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Top"> 
      </StackPanel> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 

    <uc:UcSpeler /> 
    <uc:UcSpeler /> 
    <uc:UcSpeler /> 
    <uc:UcSpeler /> 
    <uc:UcSpeler /> 
</ItemsControl> 

這我的模板:

<Style x:Key="UsersControlStyle" TargetType="{x:Type ItemsControl}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type ItemsControl}"> 
       <Border SnapsToDevicePixels="true" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"> 
        <ScrollViewer VerticalScrollBarVisibility="Visible"> 
         <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> 
        </ScrollViewer> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

回答

212

爲了得到一個滾動條爲ItemsControl,你可以在一個ScrollViewer這樣承載它:

<ScrollViewer VerticalScrollBarVisibility="Auto"> 
    <ItemsControl> 
    <uc:UcSpeler /> 
    <uc:UcSpeler /> 
    <uc:UcSpeler /> 
    <uc:UcSpeler /> 
    <uc:UcSpeler /> 
    </ItemsControl> 
</ScrollViewer> 
+1

很好,謝謝! – Xuntar 2010-01-08 16:28:28

+13

當你看到它時非常明顯......因爲我是來自Windows Forms,我經常發現自己陷入了錯誤的思維模式。看來WPF維權很多...... +1。 – 2010-11-09 08:26:14

+3

非常感謝 - 非常有幫助。我同意萊特的觀點,即我的WinForms大腦最初不會「得到」這個。 – itsmatt 2010-12-14 20:22:52

63

您必須修改控件模板,而不是ItemsPanelTemplate:

<ItemsControl > 
    <ItemsControl.Template> 
     <ControlTemplate> 
      <ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}"> 
       <ItemsPresenter /> 
      </ScrollViewer> 
     </ControlTemplate> 
    </ItemsControl.Template> 
</ItemsControl> 

也許,你的代碼不工作,因爲StackPanel有自己的滾動功能。嘗試使用StackPanel.CanVerticallyScroll屬性。

+1

的StackPanel的CanVerticallyScroll屬性沒有工作,我很害怕。 – Xuntar 2010-01-08 16:29:03

+0

StackPanel CanVerticallyScroll沒有工作,但這裏給出的代碼示例適用於我。謝謝 – 2011-05-31 18:43:54

+0

這工作。我正在尋找使scrollviewer而不是外部,因爲https://github.com/punker76/gong-wpf-dragdrop需要它。 – HelloSam 2013-07-25 05:32:25