在 DropDownButton 中使用 ScrollBar?

Use ScrollBar in DropDownButton?

我想在我的 DropDown 按钮中使用像 ComboBox 这样的滚动条,实际结构是这样的:

<Controls:DropDownButton Content="Nazioni" Width="120" Margin="0, 0, 20, 0" 
                         ScrollViewer.VerticalScrollBarVisibility="Visible"
                         ScrollViewer.CanContentScroll="True"
                         ItemsSource="{Binding Countries}"
                         ItemTemplate="{StaticResource CombinedTemplate}"/>

但我没有看到任何 ScrollViewer 如下图所示:

要确保滚动会按预期运行,您不能依赖 WPF 将 ScrollViewer 放置在应有的位置。

由于任何内容都可以放在下拉列表中,因此最好的选择是直接将 ScrollViewer 拖放到组件上。 这样,您可以显式命名它,并可以访问它的属性。 如果将国家/地区列表绑定到 lstContent 框,就可以消除所有混乱。

   <extToolkit:DropDownButton Content="Click Me" Margin="15" >
        <extToolkit:DropDownButton.DropDownContent>
            <ScrollViewer>
                <ListBox Name="lstContent" ItemsSource="{Binding Countries}" ItemTemplate="{StaticResource CombinedTemplate}"/> 
            </ScrollViewer>
        </extToolkit:DropDownButton.DropDownContent>
    </extToolkit:DropDownButton>

DropDownButton 的下拉列表已经包含一个 ScrollViewer(它被命名为 "SubMenuScrollViewer"),因此支持滚动浏览它的项目。问题是,特定 ScrollViewer 的样式不同于默认 ScrollViewer - 假设我们谈论的是垂直滚动,它在列表上方和下方有两个按钮,分别负责向上和向下滚动,如下图:

所以最好的办法是让特定的 ScrollViewer 使用默认样式而不是自定义样式。通过检查 MahApps.Metro source code,我们可以看到有问题的 ScrollViewer 连接到使用键值为 {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}} 的动态资源。因此,您需要做的是为该控件提供带有该键的默认样式:

<Controls:DropDownButton (...)>
    <Controls:DropDownButton.Resources>
        <Style x:Key="{ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}"
               TargetType="{x:Type ScrollViewer}"
               BasedOn="{StaticResource {x:Type ScrollViewer}}" />
    </Controls.DropDownButton.Resources>
</Controls.DropDownButton>

这样,下拉列表中的 ScrollViewer 将使用 MahApps.Metro.

附带的默认样式来设置样式