[英]Xamarin forms, Add new item to listview dynamically
当单击按钮时,我在Internet上找不到如何在Xamarin表单项目中动态地向列表视图添加新项的解决方案。 我在互联网上获得的唯一信息就是如何动态地从列表视图中删除项目。
那么,请问如何在单击按钮时以Xamarin形式编写代码以将新项目动态添加到列表视图中?
如果您列表的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");
}
在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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.