Xamarin表单,将新项目动态添加到列表视图

时间:2018-09-09 15:31:28

标签: xamarin.forms

在Internet上找不到单击按钮时如何在Xamarin表单项目中动态地向列表视图添加新项的解决方案。我在网上获得的唯一信息就是如何动态地从列表视图中删除项目。

因此,请问如何在单击按钮时以Xamarin形式编写代码以将新项目动态添加到列表视图?

2 个答案:

答案 0 :(得分:0)

如果列表的ItemSource是一个ObservableCollection,则只需将一个项目添加到集合中即可更新列表

ObservableCollection<string> data = new ObservableCollection<string>();

data.Add("a");
data.Add("b");
data.Add("c");

myListView.ItemSource = data;

在事件处理程序中

protected void MyButtonClick(object sender, EventArgs a) {
  data.Add("z");
}

答案 1 :(得分:0)

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