简体   繁体   English

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

[英]Xamarin.Forms: Add items to ListView from codebehind without binding?

So far I've added a map and a listview with static items to my Form. 到目前为止,我已经在表单中添加了带有静态项的地图和listview This is what the xaml looks like: 这就是xaml样子:

<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>

Instead of being static items, I would like to add them using a simple foreach loop. 我想使用简单的foreach循环添加它们,而不是使用静态项目。 This is what the loops looks like: 这是循环的样子:

    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
        }
    }

I was looking at ListView Data Sources , but they declare a collection ObservableCollection that I then bind to the ListView . 我正在查看ListView数据源 ,但是它们声明了一个ObservableCollection集合,然后将其绑定到ListView I don't want to bind my ListView to a collection; 我不想将ListView绑定到集合; I'm looking for the equivalent of this asp.net snippet (if it's possible): 我正在寻找与此asp.net代码段等效的代码(如果可能):

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

just assign your array to ItemsSource 只需将数组分配给ItemsSource

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

any IEnumerable can be used as an ItemsSource 任何IEnumerable都可以用作ItemsSource

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM