很久以前,我问过一个类似的问题:
Scrollable TextBox in WP7 (ala Skype and Facebook)
我希望在Windows Phone 8.1上有同样的行为。
我有一个文本框,用户可以在其中键入注释,当键盘启动时,它会向上移动文本框,使其始终在视图中。问题是,如果注释太大,用户无法轻松滚动整个注释。
我不想将TextBox上移,而是想调整页面大小,以便其他元素(如应用程序标题)始终可见。显然,即使注释很大,TextBox也应该很容易滚动。
这是我的XAML:
<Page
x:Class="ScrollableTextBox.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ScrollableTextBox"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<!--LayoutRoot-->
<Grid x:Name="LayoutRoot"
Margin="21,-6.5,19,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--Title-->
<TextBlock Margin="0,19,0,24"
Style="{ThemeResource TitleTextBlockStyle}"
Text="APP TITLE" />
<!--ContentPanel-->
<Grid Grid.Row="1">
<ScrollViewer x:Name="NoteContentScrollViewer">
<TextBox x:Name="NoteContentTextBox"
AcceptsReturn="True"
ScrollViewer.VerticalScrollMode="Disabled"
VerticalAlignment="Stretch"
GotFocus="NoteContentTextBox_GotFocus" />
</ScrollViewer>
</Grid>
</Grid>
下面是代码:
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace ScrollableTextBox
{
public sealed partial class MainPage : Page
{
// Handle InputPane manually so the UI doesn't scroll when the keyboard appears
InputPane inputPane = InputPane.GetForCurrentView();
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
private void NoteContentTextBox_GotFocus(object sender, RoutedEventArgs e)
{
// Subscribe InputPane events to handle UI scrolling
inputPane.Showing += this.InputPaneShowing;
inputPane.Hiding += this.InputPaneHiding;
}
private void InputPaneShowing(InputPane sender, InputPaneVisibilityEventArgs e)
{
// Set EnsuredFocusedElementInView to true so the UI doesn't scroll
e.EnsuredFocusedElementInView = true;
// Set new margins to LayoutRoot (to compensate keyboard)
LayoutRoot.Margin = new Thickness(21, -6.5, 19, e.OccludedRect.Height);
// Unsubscribe InputPane Showing event
inputPane.Showing -= this.InputPaneShowing;
}
private void InputPaneHiding(InputPane sender, InputPaneVisibilityEventArgs e)
{
// Set EnsuredFocusedElementInView to false so the UI scrolls
e.EnsuredFocusedElementInView = false;
// Reset LayoutRoot margins
LayoutRoot.Margin = new Thickness(21, -6.5, 19, 0);
// Unsubscribe InputPane Hiding event to handle UI scrolling
inputPane.Hiding -= this.InputPaneHiding;
}
}
}
这很好地工作,因为当键盘启动时,页面会被调整大小,用户可以在编辑注释时轻松滚动,并且其他UI元素不会移出视图。然而,缺少一个行为:当用户点击TextBox时,它应该滚动到插入符号位置,但现在它根本不滚动(正如我们所期望的那样)。
在WindowsPhone7上,我使用ScrollViewer.ScrollToVerticalOffset()来实现这一点,但它在WinRT上不起作用。我们应该使用ScrollViewer.ChangeView(),但我无法使其工作。
因此,简而言之,当用户点击TextBox时,我希望它滚动到插入符号位置,这样他就可以立即开始键入,而不必手动滚动(或按Enter键到达该位置)。有什么想法吗?