由子列表框的滚动触发父滚动查看器的“滚动更改”事件

问题描述 投票:0回答:1

我在滚动查看器中有一个列表框。 Scroll Viewer已附加了Scroll-Changed侦听器,在其中放置了一个:

MessageBox.Show("Something Happened!");

这是我的WPF代码:

        <ScrollViewer ScrollChanged="ScrollViewer_ScrollChanged" VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Disabled">
                <ListBox>
                    <ListBox.Items>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                        <ListBoxItem Content="item 2"/>
                    </ListBox.Items>
                </ListBox>
        </ScrollViewer>

现在的问题是,当我滚动列表框时,通过向我显示MessageBox =>发生了某种原因,ScrollViewer的'ScrollChanged'事件正在触发!

我已经尝试启用或禁用Horizo​​ntalScrollBar,但是发生了同样的事情...我的VerticalScrollBar现在已禁用,我将其设置为“隐藏”,但现在它也隐藏了ListBox的Vertical滚动条,我也无法通过鼠标滚轮滚动ListBox

提前感谢...🙂

c# wpf events scrollview parent-child
1个回答
0
投票

之所以这样,是因为ScrollViewer.ScrollChangedScrollViewer.ScrollChanged。具体来说,这是一个冒泡事件,这意味着当它升高时,它会沿着视觉树(从它被升高的更深的元素向上直到根)向上查找处理程序。

这可以让您执行以下操作:

routed event

因为<ListBox ScrollViewer.ScrollChanged="listBox_ScrollChanged"/> 在内部使用了ListBox,所以即使ScrollViewer本身没有公开事件,也可以在ScrollChanged级别监听ListBox事件并对其进行处理。

当然,这也会导致您遇到的情况。幸运的是,这很容易解决。在事件处理程序中,可以使用ListBox来指示要滚动的元素:

RoutedEventArgs.Source
© www.soinside.com 2019 - 2024. All rights reserved.