xamarin.forms - Xamarin 表单,动态添加新项目到列表视图
问题描述
当单击按钮时,我在 Internet 上找不到如何在 Xamarin 表单项目中动态地将新项目添加到列表视图的解决方案。我在互联网上得到的唯一东西是如何从列表视图中动态删除一个项目。
那么请我如何在 Xamarin 表单中编写代码以在单击按钮时动态地将新项目添加到列表视图?
解决方案
在 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>
推荐阅读
- bash - shell脚本中的动态变量赋值
- javascript - 如何使用 javascript 将用户输入存储到 SQLite3 表中?
- android - 一次加载所有 RecyclerView 项目
- java - 如何使用标准进行简单的左连接?
- android - Android 在编辑文本中使用重力时会添加 gab
- swift - 使用 AKSequencer GenData 和 LoadMIDIFile 的 AudioKit
- swift - Swift ENUM 如何将“rawValue”转换回 Enum 大小写?
- kotlin - Corda 节点监控工具或资源管理器,可用于显示除 Corda 资源管理器以外的见解
- asp.net-mvc - 支付处理期间 ProtectPay 托管支付页面超时
- python - Python3 TypeError:只能将列表(不是“str”)连接到列表