wpf 如何在ScrollViewer中仅滚动单个嵌套组件?

ct2axkht  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(124)

我有一个ScrollViewer,其中包含多个RichTextBox元素,每个元素都有垂直滚动条可见。我希望能够使用鼠标滚轮一次滚动 * 一个 * 元素:

  • 如果RichTextBox具有焦点,则滚动该
  • 否则,滚动ScrollViewer

目前,如果RichTextBox有焦点,* 和 * ScrollViewer都会滚动。我相信这是因为它们都拦截了PreviewMouseWheel-这意味着ScrollViewerRichTextBox之前“看到”事件。这意味着我不能只将事件标记为在RichTextBox中处理。
下面的repro XAML除了默认生成的代码外没有任何代码隐藏。(显然它看起来很糟糕,我的真实的应用程序 * 有点 * 好-但基本的“父ScrollViewer中的多个可滚动元素“是相同的。)

<Window x:Class="RichTextBoxMouseWheel.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="500">
    <ScrollViewer>
        <StackPanel Orientation="Vertical">
            <RichTextBox VerticalScrollBarVisibility="Visible" Height="200" Width="400" FontSize="40">
                <FlowDocument>
                    <Paragraph>Paragraph 1</Paragraph>
                    <Paragraph>Paragraph 2</Paragraph>
                    <Paragraph>Paragraph 3</Paragraph>
                </FlowDocument>
            </RichTextBox>
            <RichTextBox VerticalScrollBarVisibility="Visible" Height="200" Width="400" FontSize="40">
                <FlowDocument>
                    <Paragraph>Paragraph 1</Paragraph>
                    <Paragraph>Paragraph 2</Paragraph>
                    <Paragraph>Paragraph 3</Paragraph>
                </FlowDocument>
            </RichTextBox>
        </StackPanel>
    </ScrollViewer>
</Window>

字符串
它看起来像这样:
x1c 0d1x的数据
.并如前所述的行为-如果RichTextBox具有焦点,则ScrollViewerScrollViewer同时滚动。
有一个合理的论点是,这只是一个糟糕的UI设计开始,我应该避免嵌套滚动条。我可以 * 尝试 * 一个相当激进的重新设计,以避免这种情况,但我宁愿不,如果有一种方法,只是使现有的设计滚动,因为我想它。

7z5jn7bk

7z5jn7bk1#

这不是PreviewMouseWheel,而是MouseWheel事件。
你可以通过一个派生的控件来修复这个恼人的行为:

public class BetterRichTextBox : RichTextBox
{
    protected override void OnMouseWheel(MouseWheelEventArgs e)
    {
        base.OnMouseWheel(e);
        e.Handled = true;
    }
}

字符串

dphi5xsq

dphi5xsq2#

如果RichTextBox在您的情况下不是必需的,我建议将其更改为FlowDocumentScrollViewer

<ScrollViewer>
    <StackPanel Orientation="Vertical">
        <FlowDocumentScrollViewer Width="400"
                                  Height="200">
            <FlowDocument FontSize="40">
                <Paragraph>Paragraph 1</Paragraph>
                <Paragraph>Paragraph 2</Paragraph>
                <Paragraph>Paragraph 3</Paragraph>
            </FlowDocument>
        </FlowDocumentScrollViewer>
        <FlowDocumentScrollViewer Width="400"
                                  Height="200">
            <FlowDocument FontSize="40">
                <Paragraph>Paragraph 1</Paragraph>
                <Paragraph>Paragraph 2</Paragraph>
                <Paragraph>Paragraph 3</Paragraph>
            </FlowDocument>
        </FlowDocumentScrollViewer>
    </StackPanel>
</ScrollViewer>

字符串
https://imgur.com/gzg52Nl

相关问题