【发布时间】:2018-09-17 16:14:36
【问题描述】:
在为 UWP 平台开发应用程序时,我遇到了一个意外行为的案例。当我在一个页面上展示的内容太多时,我利用了 ScrollViewer 控件,它应该可以解决这个问题。
该控件允许滚动内容,但它处理输入的方式不自然。当控件被 Clicked 时,ScrollViewer 中没有可聚焦的控件被点击,Focus 被传递给其内容中的第一个可聚焦的控件.这实际上意味着 ScrollViewer 滚动回顶部,这不是我所期望的行为。
我希望 ScrollViewer 保持其当前位置,就像网页一样。如果要单击空白处,则网页不会滚动回第一个可聚焦控件。另一个类似的例子是 Grid 或 Stackpanel 在单击时不会将焦点传递给它的其中一个子项。
下面是一些演示上述行为的 xaml 代码,只需创建一个新的 UWP 项目 并将其放置在生成的 MainPage.xaml 的网格中:
<ScrollViewer Height="400"> <!-- Unexpected and unnatrual behavior -->
<StackPanel Width="250" Background="DarkGray" Padding="10"> <!-- With Content Height > ScrollViewer Height -->
<TextBlock Text="Unnatural scroll behavior" FontWeight="Bold"/>
<TextBox Text="Some focusable control"/>
<TextBlock Height="800" Text="On focus => pass focus to first available => scroll to the top" TextWrapping="Wrap"/>
<TextBox Text="Some focusable control"/>
</StackPanel>
</ScrollViewer>
我确实想出了一个解决方案,但是这似乎是解决当前问题的正确方法,这似乎很奇怪:
<ScrollViewer Height="400">
<!-- Corrected behaviour, but extra ContentControl. Easily forgotten -->
<ContentControl>
<StackPanel Width="250" Background="Gray" Padding="10">
<!-- With Content Height > ScrollViewer Height -->
<TextBlock Text="Corrected scroll behavior" FontWeight="Bold"/>
<TextBox Text="Some focusable control"/>
<TextBlock Height="800" Text="On focus => no scroll" TextWrapping="Wrap"/>
<TextBox Text="Some focusable control"/>
</StackPanel>
</ContentControl>
</ScrollViewer>
这可行,但是总是记得添加 ContentControl 很烦人,这就是为什么我会发布一个以更好的方式实现我的解决方案的答案。
问题仍然存在:有没有更好的方法来解决这个问题?
【问题讨论】:
标签: c# xaml uwp scrollviewer