Xamarin.Forms:从代码隐藏中将项目添加到ListView而不绑定吗?

时间:2019-02-10 18:44:10

标签: c# android xamarin xamarin.forms visual-studio-2017

到目前为止,我已经在表单中添加了地图和带有静态项目的listviewxaml如下所示:

<StackLayout>
    <StackLayout VerticalOptions="FillAndExpand">
        <maps:Map WidthRequest="960" HeightRequest="200"
        x:Name="MyMap"
        IsShowingUser="true"/>
        <ListView x:Name="ListView_Pets">
            <ListView.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>dog</x:String>
                    <x:String>cat</x:String>
                    <x:String>bird</x:String>
                </x:Array>
            </ListView.ItemsSource>
        </ListView>
    </StackLayout>
</StackLayout>

我想使用简单的foreach循环来添加它们而不是静态项目。这是循环的样子:

    public MainPage()
    {
        InitializeComponent();

        string[] pets = { "dog", "cat", "bird" };
        foreach (string pet in pets)
        {
            /* Add each pet to ListView */
            //ListView_Pets.ItemsSource.Add(pet); This doesn't build
        }
    }

我正在查看ListView Data Sources,但是他们声明了一个集合ObservableCollection,然后将其绑定到ListView。我不想将ListView绑定到集合;我正在寻找与此asp.net代码段相同的代码(如果可能):

foreach (string name in nameList)
{
    DropDownList_Pets.Items.Add(new ListItem(name));
}

1 个答案:

答案 0 :(得分:1)

只需将数组分配给ItemsSource

string[] pets = { "dog", "cat", "bird" };
ListView_Pets.ItemsSource = pets;

任何IEnumerable都可以用作ItemsSource