是否可以停止第一个条目在 Xamarin 表单中的 ScrollView 中获得焦点
Posted
技术标签:
【中文标题】是否可以停止第一个条目在 Xamarin 表单中的 ScrollView 中获得焦点【英文标题】:Is it possible to stop the first Entry getting Focus in a ScrollView in Xamarin Forms 【发布时间】:2017-07-03 00:55:39 【问题描述】:在我的申请中,我有以下情况:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:conv="clr-namespace:NumericTextBoxTest.Converters;assembly=NumericTextBoxTest"
xmlns:numericTextBox="clr-namespace:Syncfusion.SfNumericTextBox.XForms;assembly=Syncfusion.SfNumericTextBox.XForms"
x:Class="NumericTextBoxTest.MainPage">
<ScrollView>
<StackLayout>
<Entry/>
<Entry/>
<Entry/>
<Entry/>
<Entry/>
<Entry/>
<Entry/>
<Entry/>
<Entry/>
<Entry/>
</StackLayout>
</ScrollView>
</ContentPage>
现在,如果我单击底部的空白区域(条目下方),即ScrollView
,ScrollView
中的第一个 Entry
将获得焦点。
如果我要更改第一个 Entry
的值并试图取消关注 Entry
以设置值,这将非常烦人。
是否可以阻止这种行为?
【问题讨论】:
“获得焦点”是什么意思?您可以添加您所看到的行为的图像吗? 尝试添加一个隐藏控件并设置焦点:) @Krumelur 很难用图片表达我的意思。但基本上顶部的条目总是有光标在里面,你可以输入一个输入 【参考方案1】:现在,如果我单击底部的空白区域(条目下方),即 ScrollView,则 ScrollView 中的第一个条目将获得焦点。
在 UWP 中,按设计,当StackLayout
被点击时,系统将搜索StackLayout
中的每个元素,直到可以关注的第一个元素。作为解决此问题的解决方法,您可以在StackLayout
的顶部放置一个不可见的按钮。
<ScrollView>
<StackLayout>
<Button HeightRequest="0" WidthRequest="1" />
<Entry />
....
<Entry />
</StackLayout>
</ScrollView>
当StackLayout
被点击时,该按钮将被聚焦。 Entry
不会被聚焦
【讨论】:
所以这是 UWP 平台的行为方式,而不是Xamarin.Forms
?它为我的用户提供了非常糟糕的用户体验。我会尝试您的解决方法,并让您知道它是否有效
感谢您的回答。解决方法效果很好。烦人的隐形按钮需要添加到View
来阻止这种行为
感谢您的回答,它有效:我不太喜欢这个解决方案,但仅此而已。为什么 StackLayout 会有这样的行为?!
它不起作用。是的,按钮被聚焦而不是进入,但是如果你在 ScrollView 中向下滚动一点,然后单击没有元素或不可聚焦元素的地方,它会滚动到顶部! @user1 答案有效!【参考方案2】:
最后,我实际上最终覆盖了此评论中提到的默认 ScrollViewRenderer
:
https://github.com/microsoft/microsoft-ui-xaml/issues/597#issuecomment-513804526
我在 UWP 上的 ScrollViewRenderer
看起来像这样:
using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using ScrollBarVisibility = Xamarin.Forms.ScrollBarVisibility;
using UwpScrollBarVisibility = Windows.UI.Xaml.Controls.ScrollBarVisibility;
using Size = Xamarin.Forms.Size;
using Point = Xamarin.Forms.Point;
using Thickness = Xamarin.Forms.Thickness;
using FieldStrikeMove.Forms.CustomControls;
//https://github.com/microsoft/microsoft-ui-xaml/issues/597
//https://github.com/xamarin/Xamarin.Forms/blob/f17fac7b9e2225b1bfe9e94909d2b954106f8f1f/Xamarin.Forms.Platform.UAP/ScrollViewRenderer.cs
//07/01/20
[assembly: ExportRenderer(typeof(ExtendedScrollView), typeof(MyApp.UWP.CustomRenderers.Controls.ScrollViewRenderer))]
[assembly: ExportRenderer(typeof(ScrollView), typeof(MyApp.UWP.CustomRenderers.Controls.ScrollViewRenderer))]
namespace MApp.UWP.CustomRenderers.Controls
public class ScrollViewRenderer : ViewRenderer<ScrollView, ScrollViewer>//, IDontGetFocus
VisualElement _currentView;
bool _checkedForRtlScroll = false;
public ScrollViewRenderer()
AutoPackage = false;
public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
SizeRequest result = base.GetDesiredSize(widthConstraint, heightConstraint);
result.Minimum = new Size(40, 40);
return result;
protected override Windows.Foundation.Size ArrangeOverride(Windows.Foundation.Size finalSize)
if (Element == null)
return finalSize;
Element.IsInNativeLayout = true;
Control?.Arrange(new Rect(0, 0, finalSize.Width, finalSize.Height));
Element.IsInNativeLayout = false;
return finalSize;
protected override void Dispose(bool disposing)
CleanUp(Element, Control);
base.Dispose(disposing);
protected override Windows.Foundation.Size MeasureOverride(Windows.Foundation.Size availableSize)
if (Element == null)
return new Windows.Foundation.Size(0, 0);
double width = Math.Max(0, Element.Width);
double height = Math.Max(0, Element.Height);
var result = new Windows.Foundation.Size(width, height);
Control?.Measure(result);
return result;
void CleanUp(ScrollView scrollView, ScrollViewer scrollViewer)
if (Element != null)
Element.PropertyChanged -= OnContentElementPropertyChanged;
if (ContainerElement != null)
ContainerElement.LayoutUpdated -= SetInitialRtlPosition;
if (scrollView != null)
scrollView.ScrollToRequested -= OnScrollToRequested;
if (scrollViewer != null)
scrollViewer.ViewChanged -= OnViewChanged;
if (scrollViewer.Content is FrameworkElement element)
element.LayoutUpdated -= SetInitialRtlPosition;
if (_currentView != null)
_currentView.Cleanup();
protected override void OnElementChanged(ElementChangedEventArgs<ScrollView> e)
base.OnElementChanged(e);
CleanUp(e.OldElement, Control);
if (e.NewElement != null)
if (Control == null)
SetNativeControl(new ScrollViewer
HorizontalScrollBarVisibility = ScrollBarVisibilityToUwp(e.NewElement.HorizontalScrollBarVisibility),
VerticalScrollBarVisibility = ScrollBarVisibilityToUwp(e.NewElement.VerticalScrollBarVisibility),
);
Control.ViewChanged += OnViewChanged;
Element.ScrollToRequested += OnScrollToRequested;
UpdateOrientation();
UpdateContent();
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == "Content")
UpdateContent();
else if (e.PropertyName == Layout.PaddingProperty.PropertyName)
UpdateContentMargins();
else if (e.PropertyName == ScrollView.OrientationProperty.PropertyName)
UpdateOrientation();
else if (e.PropertyName == ScrollView.VerticalScrollBarVisibilityProperty.PropertyName)
UpdateVerticalScrollBarVisibility();
else if (e.PropertyName == ScrollView.HorizontalScrollBarVisibilityProperty.PropertyName)
UpdateHorizontalScrollBarVisibility();
protected void OnContentElementPropertyChanged(object sender, PropertyChangedEventArgs e)
if (e.PropertyName == View.MarginProperty.PropertyName)
UpdateContentMargins();
void UpdateContent()
if (_currentView != null)
_currentView.Cleanup();
if (Control?.Content is FrameworkElement oldElement)
oldElement.LayoutUpdated -= SetInitialRtlPosition;
if (oldElement is IVisualElementRenderer oldRenderer
&& oldRenderer.Element is View oldContentView)
oldContentView.PropertyChanged -= OnContentElementPropertyChanged;
_currentView = Element.Content;
IVisualElementRenderer renderer = null;
if (_currentView != null)
renderer = _currentView.GetOrCreateRenderer();
Control.Content = renderer != null ? renderer.ContainerElement : null;
UpdateContentMargins();
if (renderer?.Element != null)
renderer.Element.PropertyChanged += OnContentElementPropertyChanged;
if (renderer?.ContainerElement != null)
renderer.ContainerElement.LayoutUpdated += SetInitialRtlPosition;
async void OnScrollToRequested(object sender, ScrollToRequestedEventArgs e)
ClearRtlScrollCheck();
// Adding items into the view while scrolling to the end can cause it to fail, as
// the items have not actually been laid out and return incorrect scroll position
// values. The ScrollViewRenderer for android does something similar by waiting up
// to 10ms for layout to occur.
int cycle = 0;
while (Element != null && !Element.IsInNativeLayout)
await Task.Delay(TimeSpan.FromMilliseconds(1));
cycle++;
if (cycle >= 10)
break;
if (Element == null)
return;
double x = e.ScrollX, y = e.ScrollY;
ScrollToMode mode = e.Mode;
if (mode == ScrollToMode.Element)
Point pos = Element.GetScrollPositionForElement((VisualElement)e.Element, e.Position);
x = pos.X;
y = pos.Y;
mode = ScrollToMode.Position;
if (mode == ScrollToMode.Position)
Control.ChangeView(x, y, null, !e.ShouldAnimate);
Element.SendScrollFinished();
void SetInitialRtlPosition(object sender, object e)
if (Control == null) return;
if (Control.ActualWidth <= 0 || _checkedForRtlScroll || Control.Content == null)
return;
if (Element is IVisualElementController controller && controller.EffectiveFlowDirection.IsLeftToRight())
ClearRtlScrollCheck();
return;
var element = (Control.Content as FrameworkElement);
if (element.ActualWidth == Control.ActualWidth)
return;
ClearRtlScrollCheck();
Control.ChangeView(element.ActualWidth, 0, null, true);
void ClearRtlScrollCheck()
_checkedForRtlScroll = true;
if (Control.Content is FrameworkElement element)
element.LayoutUpdated -= SetInitialRtlPosition;
void OnViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
ClearRtlScrollCheck();
Element.SetScrolledPosition(Control.HorizontalOffset, Control.VerticalOffset);
if (!e.IsIntermediate)
Element.SendScrollFinished();
Windows.UI.Xaml.Thickness AddMargin(Thickness original, double left, double top, double right, double bottom)
return new Windows.UI.Xaml.Thickness(original.Left + left, original.Top + top, original.Right + right, original.Bottom + bottom);
// UAP ScrollView forces Content origin to be the same as the ScrollView origin.
// This prevents Forms layout from emulating Padding and Margin by offsetting the origin.
// So we must actually set the UAP Margin property instead of emulating it with an origin offset.
// Not only that, but in UAP Padding and Margin are aliases with
// the former living on the parent and the latter on the child.
// So that's why the UAP Margin is set to the sum of the Forms Padding and Forms Margin.
void UpdateContentMargins()
if (!(Control.Content is FrameworkElement element
&& element is IVisualElementRenderer renderer
&& renderer.Element is View contentView))
return;
var margin = contentView.Margin;
var padding = Element.Padding;
switch (Element.Orientation)
case ScrollOrientation.Horizontal:
// need to add left/right margins
element.Margin = AddMargin(margin, padding.Left, 0, padding.Right, 0);
break;
case ScrollOrientation.Vertical:
// need to add top/bottom margins
element.Margin = AddMargin(margin, 0, padding.Top, 0, padding.Bottom);
break;
case ScrollOrientation.Both:
// need to add all margins
element.Margin = AddMargin(margin, padding.Left, padding.Top, padding.Right, padding.Bottom);
break;
void UpdateOrientation()
//Only update the horizontal scroll bar visibility if the user has not set a desired state.
if (Element.HorizontalScrollBarVisibility != ScrollBarVisibility.Default)
return;
var orientation = Element.Orientation;
if (orientation == ScrollOrientation.Horizontal || orientation == ScrollOrientation.Both)
Control.HorizontalScrollBarVisibility = UwpScrollBarVisibility.Auto;
else
Control.HorizontalScrollBarVisibility = UwpScrollBarVisibility.Disabled;
UwpScrollBarVisibility ScrollBarVisibilityToUwp(ScrollBarVisibility visibility)
switch (visibility)
case ScrollBarVisibility.Always:
return UwpScrollBarVisibility.Visible;
case ScrollBarVisibility.Default:
return UwpScrollBarVisibility.Auto;
case ScrollBarVisibility.Never:
return UwpScrollBarVisibility.Hidden;
default:
return UwpScrollBarVisibility.Auto;
void UpdateVerticalScrollBarVisibility()
Control.VerticalScrollBarVisibility = ScrollBarVisibilityToUwp(Element.VerticalScrollBarVisibility);
void UpdateHorizontalScrollBarVisibility()
var horizontalVisibility = Element.HorizontalScrollBarVisibility;
if (horizontalVisibility == ScrollBarVisibility.Default)
UpdateOrientation();
return;
var orientation = Element.Orientation;
if (orientation == ScrollOrientation.Horizontal || orientation == ScrollOrientation.Both)
Control.HorizontalScrollBarVisibility = ScrollBarVisibilityToUwp(horizontalVisibility);
public static class Extensions
internal static void Cleanup(this VisualElement self)
if (self == null)
throw new ArgumentNullException("self");
IVisualElementRenderer renderer = Platform.GetRenderer(self);
foreach (Element element in self.Descendants())
var visual = element as VisualElement;
if (visual == null)
continue;
IVisualElementRenderer childRenderer = Platform.GetRenderer(visual);
if (childRenderer != null)
childRenderer.Dispose();
Platform.SetRenderer(visual, null);
if (renderer != null)
renderer.Dispose();
Platform.SetRenderer(self, null);
【讨论】:
感谢您的回答。将 IsTabStop 设置为 true 不会执行任何操作。这行得通!所以问题是 IDontGetFocus 接口!这应该是公认的答案。 我在 ios 上的 Xamarin.Forms 应用程序上看到了相同(或非常相似)的问题,但此解决方案不适用。有人解决了 iOS 的问题吗? @CMPalmer 我还没有在 iOS 上看到它,虽然我必须承认我没有在 iOS 上测试过更高版本的 XF。我会看看Xamarin.Forms github issues 看看是否还有其他人有问题【参考方案3】:如果我点击底部的空白处(条目下方)
您可以拉伸您的堆栈布局,然后它将获得焦点而不是滚动视图。
您还可以为 stacklayout 设置 backgroundcolor 以确保 stacklayout 被拉伸
【讨论】:
【参考方案4】:[更新]
我刚刚发现,当类与 Xamarin Forms 中的类具有相同的名称时,我确实需要完全限定我的自定义 ScrollViewRenderer
的命名空间,以用于 ExportRenderer
属性的 Target
参数。
现在它按预期工作
[原创]
我尝试实现 User1 发布的 CustomRenderer,但它似乎没有在 UWP 项目中使用。尽管我在页面上有 ScrollView
,但从未调用过 ScrollViewRenderer
的构造函数。
如果我从ScrollView
派生CustomScrollView
并让渲染器应用于CustomScrollView
,它会被使用并且解决方法按预期工作,但似乎我无法覆盖所有滚动视图的渲染器。
任何提示为什么不使用渲染器来替换 XF 的默认内置 ScrollViewRenderer? (顺便说一句。我使用的是 XF 5.0.0.1874)
【讨论】:
以上是关于是否可以停止第一个条目在 Xamarin 表单中的 ScrollView 中获得焦点的主要内容,如果未能解决你的问题,请参考以下文章
从 ViewModel Xamarin 中的动态表单中获取条目值
当条目字段不可见时,如何隐藏 Xamarin 表单中的错误标签?
如何在 UWP 上的 Xamarin 表单条目中垂直居中文本?