【.NET MAUI】入力画面で入力した内容を遷移先の画面で表示する
ListView を表示する画面
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="MauiApp14.MainPage"> <ScrollView> <VerticalStackLayout Spacing="25" Padding="30,0" VerticalOptions="Start"> <ListView x:Name="TodoListView" SeparatorVisibility="Default"> <ListView.ItemTemplate> <DataTemplate> <TextCell Text="{Binding Title}" Detail="{Binding Detail}" /> </DataTemplate> </ListView.ItemTemplate> </ListView> <Button x:Name="MoveBtn" Text="追加" Clicked="OnMoveClicked" HorizontalOptions="End" /> </VerticalStackLayout> </ScrollView> </ContentPage>
コード側に入力画面からパラメータを受け取れるように QueryProperty属性を付ける。
using System.Collections.ObjectModel; namespace MauiApp14; // 最初の引数はデータを受け取るプロパティの名前を指定し、2番目の引数はパラメーターID を指定 [QueryProperty(nameof(AddTodo), "Todo")] public partial class MainPage : ContentPage { static ObservableCollection<TodoItem> TodoList = new(); List<TodoItem> TodoItems = new(); public MainPage() { InitializeComponent(); TodoListView.ItemsSource = TodoList; } private async void OnMoveClicked(object sender, EventArgs e) { await Shell.Current.GoToAsync(nameof(NewPage1)); } public TodoItem AddTodo { set { TodoList.Add(value); } } } public sealed class TodoItem { public TodoItem(string title, string detail) { Title = title; Detail = detail; } public string Title { get; set; } public string Detail { get; set; } }
入力画面
NewPage1.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="MauiApp14.NewPage1" Title="TODO入力"> <ScrollView> <VerticalStackLayout VerticalOptions="Center"> <Entry x:Name="TitleEntry" Placeholder="タイトル" /> <Entry x:Name="DetailEntry" Placeholder="詳細" /> <Button Text="追加" Clicked="OnAddClicked" /> </VerticalStackLayout> </ScrollView> </ContentPage>
namespace MauiApp14; public partial class NewPage1 : ContentPage { public NewPage1() { InitializeComponent(); } private async void OnAddClicked(object sender, EventArgs e) { var todo = new TodoItem(TitleEntry.Text, DetailEntry.Text); var navigationParameter = new Dictionary<string, object> { { "Todo", todo } }; await Shell.Current.GoToAsync($"//{nameof(MainPage)}", navigationParameter); } }
Todo というキーで MainPage に入力内容のデータを渡す。
画面遷移の設定
AppShell.xaml
<?xml version="1.0" encoding="UTF-8" ?> <Shell x:Class="MauiApp14.AppShell" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:MauiApp14" Shell.FlyoutBehavior="Disabled"> <ShellContent Title="Home" ContentTemplate="{DataTemplate local:MainPage}" Route="MainPage" /> </Shell>
namespace MauiApp14; public partial class AppShell : Shell { public AppShell() { InitializeComponent(); Routing.RegisterRoute(nameof(NewPage1), typeof(NewPage1)); } }
実行
最初は何もない
入力画面
追加ボタンを押すと最初の画面に戻ってListView に入力内容を反映する