如何使用内部ArrayItems在Listview中添加动态值?

时间:2018-03-15 05:33:59

标签: xamarin xamarin.forms

我是xamarin的新手,我有一个listview,其中包含两个标签和一个字符串数组。如何在listview中绑定这些项目? 根据数据,项目可以是1到5。

image

2 个答案:

答案 0 :(得分:1)

您可以创建ContentView作为StackLayout的容器。然后,您可以将string[]属性绑定到ContentView的{​​{1}}属性。最后,您可以使用值转换器将Content值转换为水平string[]

例如:

StackLayout

只需将<ContentPage ... xmlns:local="clr-namespace:MyProject.MyValueConverters"> <ContentPage.Resources> <ResourceDictionary> <local:ArrayToStackLayoutConverter x:Key="arrayToStackLayout" /> </ResourceDictionary> </ContentPage.Resources> ... ... place the ContentView wherever you want the labels to appear ... <ContentView Margin="0" Padding="0" Content="{Binding MyStringArray, Converter={StaticResource arrayToStackLayout}}" /> ... </ContentPage> 放在<ContentView />的{​​{1}}内,即可显示任何项目数组。

然后是值转换器:

ListView

答案 1 :(得分:0)

class MyItem {
   public string Label1 {get; set;}
   public string Label2 {get; set;}
   public string[] Subitems {get; set;}
}

//viewmodel is something like List<MyItem>
List<MyItem> viewModel = GetDataFromService(...);

//xaml
<ListView BindingContext="viewModel">  //i can't remember exactly, maybe use <ListView.ItemSource>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Label Text="{Binding Label1}" />
            <Label Text="{Binding Label2}" />
            <ListView BindingContext="Subitems">
               <ListView.ItemTemplate>
                  <DataTemplate>
                    <BoxView ...> //set height, weight, border
                      <Label
                    </BoxView>
                 </DataTemplate>
           </ListView>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

总而言之,在外部ListView中使用内部ListView。