Xamarin表单,动态添加新项目到listview

问题描述 投票:0回答:2

在单击按钮时,我无法在互联网上找到如何在Xamarin表单项目中动态地向listview添加新项目的解决方案。我在互联网上获得的唯一内容是如何动态删除listview中的项目。

那么请问我如何在Xamarin表单中编写代码,以便在单击按钮时动态地向listview添加新项目?

xamarin.forms
2个回答
0
投票

如果List的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");
}

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>
© www.soinside.com 2019 - 2024. All rights reserved.