当组合框移动时处理组合框下拉

时间:2014-12-22 04:53:14

标签: wpf combobox scrollviewer

我们的WPF应用程序有一个包含各种控件的ScrollViewer。当打开带有此ScrollViewer的组合框,然后用户使用鼠标滚轮滚动ScrollViewer时,组合框控件会移动,但下拉列表仍保持在同一位置,这看起来很尴尬。

当ScrollViewer滚动并更改组合框位置时,是否有一种简单的方法可以使组合框关闭,或下拉列表的位置更新?

我知道我可以处理鼠标滚轮事件,但是我有很多这样的情况,ScrollViewer中包含一个组合框,并且很想听听更好的解决方案。

2 个答案:

答案 0 :(得分:0)

您可以处理ScrollChanged的{​​{1}}事件并强制ScollViewer关闭DropDown菜单: XAML

ComboBox

并在后面的代码中:

 <ScrollViewer  VerticalAlignment="Stretch" HorizontalAlignment="Stretch" ScrollChanged="ScrollViewer_OnScrollChanged">
       <Grid Height="700">
            <ComboBox x:Name="comboBox" VerticalAlignment="Center" HorizontalAlignment="Center">
                <ComboBoxItem Content="Elt One"/>
                <ComboBoxItem Content="Elt Two"/>
                <ComboBoxItem Content="Elt Three"/>
            </ComboBox>
        </Grid>
   </ScrollViewer>

答案 1 :(得分:0)

我通过在App.xaml.cs中添加以下代码来处理它:

EventManager.RegisterClassHandler(typeof(ComboBox), UIElement.GotFocusEvent, new RoutedEventHandler(SetSelectedComboBox));
EventManager.RegisterClassHandler(typeof(ScrollViewer), UIElement.MouseWheelEvent, new MouseWheelEventHandler(OnMouseWheelEvent));

private static WeakReference<ComboBox> _selectedComboBox;

private static void SetSelectedComboBox(object sender, RoutedEventArgs e)
{
    _selectedComboBox = new WeakReference<ComboBox>(sender as ComboBox);
}

// Close dropdown when scrolling with the mouse wheel - QM001866525
private static void OnMouseWheelEvent(object sender, MouseWheelEventArgs e)
{
    if (_selectedComboBox == null || Environment.GetEnvironmentVariable("DONT_CLOSE_COMBO_ON_MOUSE_WHEEL") == "1")
    {
        return;
    }

    ComboBox combo;
    if (_selectedComboBox.TryGetTarget(out combo) && combo.IsDropDownOpen)
    {
        combo.IsDropDownOpen = false;
    }
}
相关问题