Home > Software engineering >  WPF Make scrollviewer work always, not just when mouse is located ont it
WPF Make scrollviewer work always, not just when mouse is located ont it

Time:01-13

I have a scrollviewer with a stackpanel and buttons inside. I can use the mouse wheel to scroll it if the mouse is hovering over the scrollviewer. Is there any way i could make it so the mousewheel works no matter the location of the mouse?

Here is my XAML Code:


<Grid PreviewMouseWheel="ScrollViewMain_PreviewMouseWheel">
        <ScrollViewer x:Name="ScrollViewMain"
                      LostFocus="ScrollViewMain_LostFocus"
                      PreviewMouseWheel="ScrollViewMain_PreviewMouseWheel"
                      VerticalScrollBarVisibility="Disabled" 
                      HorizontalScrollBarVisibility="Visible"
                      PanningMode="HorizontalOnly"
                      CanContentScroll="False"
                      
                      Height="150" VerticalAlignment="Top" Margin="0,162,0,0">
            <StackPanel  Orientation="Horizontal">
                <Button Width="100" Height="100" Margin="10,10,10,10"></Button>
                <Button Width="100" Height="100" Margin="10,10,10,10"></Button>
                <Button Width="100" Height="100" Margin="10,10,10,10"></Button>
                <Button Width="100" Height="100" Margin="10,10,10,10"></Button>
                <Button Width="100" Height="100" Margin="10,10,10,10"></Button>
                <Button Width="100" Height="100" Margin="10,10,10,10"></Button>
                <Button Width="100" Height="100" Margin="10,10,10,10"></Button>
                <Button Width="100" Height="100" Margin="10,10,10,10"></Button>

            </StackPanel>
        </ScrollViewer>
    </Grid>

My code-behind:

 private void ScrollViewMain_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            ScrollViewer scrollViewer = ScrollViewMain;
            if (e.Delta >0)
            {
                scrollViewer.LineLeft();
            }
            else
            {
                scrollViewer.LineRight();
            }
            e.Handled = true;
        }

I tried this but that sadly didn't work:


 private void ScrollViewMain_LostFocus(object sender, RoutedEventArgs e)
        {
            ScrollViewMain.Focus();
        }

My thought behind this was that i could force the scrollviewer to be focused.

Thanks for your time!

CodePudding user response:

Oh, how I understand your pain, it happened to me on several occasions...
The reason is that your grid does not have background and the mouse events simply fall through it.

The solution is to add Background="Transparent" to your grid.

  • Related