简体   繁体   中英

Mousewheel scrolling on a Listbox within a Ribbon [WPF]

I have a Ribbon with two tabs and one of the tabs contains a listbox , with auto-generated content.

I would like the mouse wheel to scroll through the listbox content and have tried lots of things, but the mouse wheel only ever switches Ribbon tabs.

Below is one solution I have tried where I attempt to release mouse the mouse control from the Ribbon and give it to the ListBox but, so far I have been unsuccessful. Is there a proper way to do this? Am I missing something?

xaml

<Ribbon Name="ribbonMain">
   <RibbonTab Header="Home">
      <RibbonGroup Header="Employees" Width="200">
         <ListBox x:Name="empListBox" ItemsSource="{Binding SelectedEmployees}" 
             Width="180" 
             MouseEnter="empListBox_MouseEnter" 
             MouseLeave="empListBox_MouseLeave">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <CheckBox Content="{Binding Path=FirstName}" IsChecked="{Binding IsChecked}"></CheckBox>
                    </DataTemplate>
                </ListBox.ItemTemplate>
          </ListBox>
     </RibbonGroup>

xaml.cs

 private void empListBox_MouseEnter(object sender, MouseEventArgs e)
    {
        if (sender is ListBox)
        {
            ribbonMain.ReleaseMouseCapture();
            ((ListBox)sender).CaptureMouse();
        }
    }

    private void empListBox_MouseLeave(object sender, MouseEventArgs e)
    {
        ((ListBox)sender).ReleaseMouseCapture();
        ribbonMain.CaptureMouse();
    }

I think the problem is that the ListBox itself can't really do anything with the mouse capture. I think it's actually the scroll viewer inside the ListBox template that needs to receive the wheel events.

Try changing your mouse handlers like so:

private void empListBox_MouseEnter(object sender, MouseEventArgs e)
{
    Mouse.Capture(empListBox, CaptureMode.SubTree);
}

private void empListBox_MouseLeave(object sender, MouseEventArgs e)
{
    empListBox.ReleaseMouseCapture();
}

This will make mouse events visible to the element holding the capture * and* its descendant elements, including the scroll viewer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM