首页 > 解决方案 > Xamarin 表单,动态添加新项目到列表视图

问题描述

当单击按钮时,我在 Internet 上找不到如何在 Xamarin 表单项目中动态地将新项目添加到列表视图的解决方案。我在互联网上得到的唯一东西是如何从列表视图中动态删除一个项目。

那么请我如何在 Xamarin 表单中编写代码以在单击按钮时动态地将新项目添加到列表视图?

标签: xamarin.forms

解决方案


在 MainPage.xaml.cs 的代码中,假设你有一个类 Person

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

private ObservableCollection<Person> _persons;
public ObservableCollection<Person> Persons
{
    get
    {
        return _persons ?? (_persons = new ObservableCollection<Person>());
    }
}

在点击按钮事件处理程序(代码后面):

private void Button_OnClicked(object sender, EventArgs e)
{
    //create person here 
    var person = new Person()
    {
        Name = "toumir",
        Age = 25
    };

    //add the created person to the list
    Persons.Add(person);
}

MainPage.xaml 页面如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:App2"
             x:Class="App2.MainPage">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackLayout Grid.Row="0">
            <Button Clicked="Button_OnClicked" Text="Add Person"/>
        </StackLayout>

        <ListView Grid.Row="1" ItemsSource="{Binding Persons}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                         <StackLayout Margin="1">
                            <Label Text="{Binding Name}"/>
                            <Label Text="{Binding Age}"/>
                        </StackLayout>
                        <ViewCell.ContextActions>
                            <MenuItem Text="test"></MenuItem>
                        </ViewCell.ContextActions>
                        </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</ContentPage>

推荐阅读