.NET MAUI中如何将用户输入添加至页面列表?
.NET MAUI 实现输入内容添加到列表功能
要实现输入框内容点击按钮后添加到列表的功能,你需要做以下几个关键修改:
- 声明可观察集合存储输入内容:
ObservableCollection能自动通知UI更新,适合绑定到ListView - 设置页面绑定上下文:让XAML中的绑定能找到对应的数据源
- 完善按钮点击逻辑:获取输入、添加到集合、清空输入框
- 配置
ListView的项模板:指定列表项的显示样式
修改后的MainPage.xaml.cs
using System.Collections.ObjectModel; namespace MauiApp1 { public partial class MainPage : ContentPage { // 用ObservableCollection存储所有输入的名称,支持自动UI更新 public ObservableCollection<MyName> MyNames { get; set; } = new ObservableCollection<MyName>(); public MainPage() { InitializeComponent(); // 将绑定上下文设为当前页面,确保XAML能访问MyNames属性 BindingContext = this; } private void AddInputItemToList(object sender, EventArgs e) { // 获取输入框文本并去除前后空格 string inputText = entry.Text?.Trim(); // 避免添加空内容 if (!string.IsNullOrEmpty(inputText)) { MyNames.Add(new MyName { Name = inputText }); // 添加后清空输入框 entry.Text = string.Empty; } } } public class MyName { public string Name { get; set; } } }
修改后的MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MauiApp1.MainPage"> <ScrollView> <VerticalStackLayout Margin="20" Spacing="25" Padding="30,0" VerticalOptions="Center"> <Entry x:Name="entry" MaxLength="255" MinimumWidthRequest="500" Placeholder="Name" FontSize="18" HorizontalOptions="Center" /> <Button x:Name="AddToList" Text="Add" Clicked="AddInputItemToList" HorizontalOptions="Center" /> <!-- 绑定到MyNames集合,并通过ItemTemplate指定显示样式 --> <ListView ItemsSource="{Binding MyNames}"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Label Text="{Binding Name}" FontSize="18" Margin="10"/> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> </VerticalStackLayout> </ScrollView> </ContentPage>
关键说明
- ObservableCollection:替代普通
List,因为它实现了INotifyCollectionChanged接口,集合内容变化时会自动触发ListView更新 - 绑定上下文:设置
BindingContext = this后,XAML中的{Binding MyNames}才能找到页面类中的对应属性 - ListView项模板:必须指定
ItemTemplate,否则ListView无法知道如何渲染每一项内容,这里用Label绑定到MyName的Name属性 - 输入校验:添加前判断输入是否为空,避免无效内容,同时清空输入框提升用户体验
内容的提问来源于stack exchange,提问作者DktPhl2018
相关产品推荐
相关产品推荐

