【问题标题】:Xamarin Forms AutomationId on ListView itemsListView 项目上的 Xamarin 表单 AutomationId
【发布时间】:2019-09-19 09:00:16
【问题描述】:

我正在尝试使用 Xamarin Forms 中的 AutomationId 可绑定属性来更好地与 Tosca 自动化配合使用。我有一个 ListView,假设我用“Test”类型的对象列表填充它,称为 TestList。我基本上想将 AutomationId 设置为“Test-{TestList.indexOf(testObject)}”。

我已经尝试将它绑定到一个递增的 ID,但如果一个屏幕上有两个 ListView,这将无济于事。没有办法从另一个列表中唯一地识别一个列表。我需要对象类型 + 唯一 ID。

如果我用 3 个“测试”对象填充列表,最终结果会将 ContentDescriptions 设置为:Test0、Test1、Test2

有人知道是否有“行业标准”或简单、可维护的方法吗?

【问题讨论】:

  • 如果同一页面上有两个列表视图,那么为什么不简单地放置命名约定!像“List1Test-1”、“List2Test-1”?您所说的所有其他内容都已经在使用可绑定索引。我认为这应该都很好。
  • @NirmalSubedi 抱歉,我可能措辞不佳,我实际上不明白如何将 AutomationId 设置为“Test0”。你知道如何将该值设置为索引,以对象类型为前缀吗?
  • 您可以发布您正在使用的模型吗?测试对象中是否有任何与数据相关的 ID?或者你只是想使用索引?

标签: c# xaml xamarin.forms xamarin.forms.listview


【解决方案1】:

这只是一个例子。代码可能无法正常工作,因为我输入的是 SO Editor 而不是任何代码编辑器。希望你理解:

型号:

public class TestObject
{
    public string Id {get;set;}
    public string DisplayText {get;set;}
}

视图模型:

public class TestPageViewModel
{
     public ObservableList<TestObject> TestObjects= new ObservableList<TestObject>();

     //Skipped all Data initialization logics.
}

Xaml 第一列表:

<ListView x:Name="List1" AutomationId="List1" ItemSource="{Binding TestObjects">
    <ListView.ItemTemplate>
         <DataTemplate>
              <ViewCell>
                   <StackLayout Orientation="Horizontal" AutomationId="{Binding Id,StringFormat='$List1Test{0}'}">
                        <!-- Rest of your Xaml -->
                   </StackLayout>
              <ViewCell>
         <DataTemplate>
    <ListView.ItemTemplate>          
</ListView>

第二名单:

<ListView x:Name="List2" AutomationId="List2" ItemSource="{Binding TestObjects">
    <ListView.ItemTemplate>
         <DataTemplate>
              <ViewCell>
                   <StackLayout Orientation="Horizontal" AutomationId="{Binding Id,StringFormat='$List2Test{0}'}">
                        <!-- Rest of your Xaml -->
                   </StackLayout>
              <ViewCell>
         <DataTemplate>
    <ListView.ItemTemplate>          
</ListView>

【讨论】:

  • 我希望模型本身没有任何东西,但不要认为有任何其他方式。不过谢谢,这是我最终采用的方法!
  • 在列表视图中,导致错误无法分配属性“AutomationId”:属性不存在,或不可分配,或值和属性之间的类型不匹配跨度>
  • &lt;Switch AutomationId="{Binding Id,StringFormat='switch__{0}'}" IsToggled="{Binding ToggleChange}" VerticalOptions="CenterAndExpand" HorizontalOptions="EndAndExpand"&gt;&lt;/Switch&gt;
  • 确保您使用的是支持可绑定自动化 id 的 Xamarin.Forms 版本:https://github.com/xamarin/Xamarin.Forms/issues/3845
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 2018-08-13
  • 1970-01-01
  • 2021-09-17
  • 2019-04-12
  • 1970-01-01
相关资源
最近更新 更多