将AutomationID与ListView一起使用

我正在尝试将automationId附加到listview中的项目。 理想情况下,通过将项目名称绑定到显示的项目。

 

当我到达页面时,代码正在部署但没有运行,是否有人找到了一个很好的解决方法来绑定ID?

从长远来看,我希望将它与Xamarin Forms能力一起使用,滚动可以滚动到标记的项目,但不滚动到显示的文本。

AutomationId不是可绑定属性,如Xamarin.Forms源代码中所示:

Xamarin.Forms.Core.Element.cs

 string _automationId; public string AutomationId { get { return _automationId; } set { if (_automationId != null) throw new InvalidOperationException("AutomationId may only be set one time"); _automationId = value; } } 

有几个人在Xamarins用户语音中提出了这个问题。

您需要在此期间对AutomationId进行硬编码,并构建具有硬编码ID的UI测试。

我通过使用附加属性作为我可以绑定到的代理来解决这个问题:

 public class AutomationBinding { #region AutomationId Attached Property public static readonly BindableProperty AutomationIdProperty = BindableProperty.CreateAttached (nameof(AutomationIdProperty), typeof(string), typeof(AutomationBinding), string.Empty, propertyChanged: OnAutomationIdChanged); public static string GetAutomationId(BindableObject target) { return (string)target.GetValue(AutomationIdProperty); } public static void SetAutomationId(BindableObject target, string value) { target.SetValue(AutomationIdProperty, value); } #endregion static void OnAutomationIdChanged(BindableObject bindable, object oldValue, object newValue) { // Element has the AutomationId property var element = bindable as Element; string id = (newValue == null) ? "" : newValue.ToString(); // we can only set the AutomationId once, so only set it when we have a reasonable value since // sometimes bindings will fire with null the first time if (element != null && element.AutomationId == null && !string.IsNullOrEmpty(id)) { element.AutomationId = id; } } } 

然后可以在xaml中使用,如下所示: