将AutomationID与ListView一起使用



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

<ListView
ItemsSource="{Binding Projects}"
AutomationId="{Binding Projects}
HasUnevenRows="True"
IsPullToRefreshEnabled="true"
CachingStrategy="RecycleElement"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">  

当我到达页面时,代码正在部署但没有运行,有人找到这样绑定ID的好方法吗?

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

AutomationId不是Xamarin中明显的可绑定属性。窗体源代码:

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 User Voice上有几个人提出了这个问题。

在此期间,您需要对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中使用:

<Button local:AutomationBinding.AutomationId="{Binding}" Text="{Binding}"/>

最新更新