我正在尝试将automationId附加到listview中的项目。理想情况下,通过将项目名称绑定到显示的项目。
<ListView
ItemsSource="{Binding Projects}"
AutomationId="{Binding Projects}
HasUnevenRows="True"
IsPullToRefreshEnabled="true"
CachingStrategy="RecycleElement"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
当我到达页面时代码正在部署但没有运行,是否有人找到了一个很好的解决方法来绑定ID?
长期来说,我希望将它与Xamarin Forms功能一起使用,可以滚动到标记的项目,但不能滚动到显示的文本。
答案 0 :(得分:4)
AutomationId
不是可绑定属性,如Xamarin.Forms源代码中所示:
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测试时。
答案 1 :(得分:3)
我通过使用附加属性作为我可以绑定的代理来解决这个问题:
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}"/>