使用按钮在组合框中滚动

时间:2013-09-17 08:59:15

标签: c# wpf xaml combobox scroll

我希望我们的用户能够在组合框中滚动按钮

我已自定义style的{​​{1}}和ItemContainerStyle

现在我不知道如何从代码隐藏中访问ComboBox中的ScrollViewer,并为按钮添加事件处理程序。我想我是在正确的方式,但我现在卡住了。

这就是我想要完成的事情:

the goal

  • 我的ComboBox中的ComboBox

    MainWindow

我的<ComboBox x:Name="cb" Style="{StaticResource ComboBoxStyle}" ItemContainerStyle="{staticResource ComboBoxItemStyle1}" IsDropDownOpen="True"> <ComboBoxItem Content="ComboBoxItem"/> <ComboBoxItem Content="ComboBoxItem"/> <ComboBoxItem Content="ComboBoxItem"/> <ComboBoxItem Content="ComboBoxItem"/> <ComboBoxItem Content="ComboBoxItem"/> </ComboBox>

ItemcontainerStyle

<Style x:Key="ComboBoxItemStyle1" TargetType="{x:Type ComboBoxItem}"> <Setter Property="Padding" Value="0"/> <Setter Property="Background" Value="Transparent"/> <Setter Property="Foreground" Value="#FFE8E8E8"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ComboBoxItem}"> <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true" Padding="0,10" Margin="0"> <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" HorizontalAlignment="Center" VerticalAlignment="Stretch" Margin="0" /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsHighlighted" Value="true"> <Setter Property="Background" TargetName="Bd" Value="#FF214174"/> <Setter Property="Foreground" Value="#FFE8E8E8"/> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> 的样式:

ComboBox

2 个答案:

答案 0 :(得分:2)

您需要为ScrollViewer提供一个名称才能访问它。你也可以很容易地将它保存在xaml中,以实现你想要的功能:

所以说我将ScrollViewer名称指定为:

<ScrollViewer x:Name="someScroll"
              ...>

现在将RepeatButton修改为:

<RepeatButton Command="{x:Static ScrollBar.LineUpCommand}"
              CommandTarget="{Binding ElementName=someScroll}"
              ... />
<RepeatButton Command="{x:Static ScrollBar.LineDownCommand}"
              CommandTarget="{Binding ElementName=someScroll}"
              ... />

ScrollBar Fields列出了可供使用的其他命令,类似于ScrollBar.LineDownCommand / ScrollBar.LineUpCommand

答案 1 :(得分:1)

如果您为ScrollViewer命名,则可以轻松访问它:

<ScrollViewer x:Name="ScrollViewer" Grid.Row="0"  CanContentScroll="true" 
    VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" 
    HorizontalAlignment="Stretch" Margin="0,0,0,40" Padding="0" Foreground="#00000000">
    <ItemsPresenter Margin="0"  />
</ScrollViewer>

然后您应该能够像这样访问它:

ScrollViewer scrollViewer = (ScrollViewer)cb.Template.FindName("ScrollViewer", cb);