如何将 Home/End 按钮按下传播到 WPF ScrollViewer 内的 UWP RichEditBox?

How to propagate Home/End button press to a UWP RichEditBox inside of a WPF ScrollViewer?

在 windows 之一的 WPF 应用程序(针对 .NET core 3.1)中,我有一个 ScrollViewer 并且在 ScrollViewer 中(以及其他元素)我放置了一个自定义 UWP 控件,其中包含一个 RichEditBox。我通过 XamlHosts:

添加了这个自定义 UWP 控件
<Window xmlns:xaml="clr-namespace:Microsoft.Toolkit.Wpf.UI.XamlHost;assembly=Microsoft.Toolkit.Wpf.UI.XamlHost">
    ...
     <ScrollViewer>
        <Grid>
            ...
            <xaml:WindowsXamlHost InitialTypeName="UWPControls.MyRichBox" x:Name="UwpRichEditBox"/>
        </Grid>
    </ScrollViewer>
<Window>

UWP 样式的 RichEditBox 出现在 WPF 应用程序中,我可以键入文本,使用箭头按钮移动插入符号,但一些关键事件不起作用。例如,我不能使用 Home/End 按钮转到 RichEditBox 中一行的开头或结尾。

问题在于,WPF 应用程序中的 ScrollViewer 会捕获这些按钮按下操作 (Home/End/Ctrl+Right-Left),并且它不会传播到 Xaml Island RichEditBox 控件。我知道这一点,因为如果我删除 ScrollViewer,问题就会消失。

我尝试为 ScrollViewer 设置 Focusable="False"IsTabStop="False",但没有帮助。我可以在 WPF 中捕获这些键盘事件,但在 XamlIsland UWP 控件中,当我按下 Home 或 End 按钮(也不是 KeyDownEventPreviewKeyDownEvent).对于其他键,它们会被触发。

我能否以某种方式阻止 ScrollViewer 捕获键盘事件?或者当我在 WPF 中捕获它们时,我可以以某种方式在 UWP RichEditBox 上引发键盘事件吗?

我终于可以解决这个问题了,方法是对 ScrollViewer 进行子类化并重写 OnKeyDown 方法。

namespace MyNameSpace.Custom {
    public class MyScrollViewer : ScrollViewer {
        protected override void OnKeyDown(KeyEventArgs e) {
            // do nothing!
        }
    }
}

然后在XAML视图中使用这个控件

<Window x:Class="..."
        xmlns:custom="clr-namespace:MyNameSpace.Custom">
    <custom:MyScrollViewer>
        ....
    </custom:MyScrollViewer>
</Window>