0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#初心者向け】.NET MAUIでTodoアプリを作るステップバイステップ解説(その3)

Posted at

はじめに

前回の記事の続きになります。

今回は、DBから全タスクを取得し、タスク一覧を表示する画面を作成します。


タスク取得メソッドの作成

MongoDbService.cs を編集します。

// ToDoList\Services\MongoDbService.cs
using MongoDB.Bson;
using MongoDB.Driver;
using System.Diagnostics;
using System;
using ToDoList.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ToDoList.Services
{
    public class MongoDbService
    {
        private readonly MongoClient _client;
        private readonly IMongoCollection<TodoItem> _collection;

        public MongoDbService()
        {
            const string connectionUri = "接続文字列";

            try
            {
                var settings = MongoClientSettings.FromConnectionString(connectionUri);
                settings.ServerApi = new ServerApi(ServerApiVersion.V1);
                _client = new MongoClient(settings);
                var database = _client.GetDatabase("todo_app");
                _collection = database.GetCollection<TodoItem>("tasks");
                Debug.WriteLine("✅ MongoDBに接続成功しました");
            }
            catch (Exception ex)
            {
                Debug.WriteLine("❌ MongoDB接続失敗: " + ex.Message);
            }
        }

        public async Task<List<TodoItem>> GetTodoItemsAsync()
        {
            try
            {
                var tasks = await _collection.Find(_ => true).ToListAsync();
                Debug.WriteLine($"📋 取得したタスク数: {tasks.Count}");
                foreach (var task in tasks)
                {
                    Debug.WriteLine($"✔️ タイトル: {task.Title} / 締切: {task.DueDate:yyyy-MM-dd} / 完了: {task.IsCompleted}");
                }

                return tasks;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("❌ タスク取得失敗: " + ex.Message);
                return new List<TodoItem>();
            }
        }
    }
}

タスク一覧の表示画面の作成

<?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="ToDoList.MainPage"
             Title="タスク一覧">

    <VerticalStackLayout Padding="20" Spacing="10">
        <CollectionView x:Name="TaskCollectionView"
                        ItemsLayout="VerticalList"
                        SelectionMode="None">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <StackLayout Orientation="Horizontal" Padding="10">
                        <Label Text="{Binding Title}" FontAttributes="Bold" />
                        <Label Text="{Binding DueDate, StringFormat='(締切: {0:yyyy/MM/dd})'}"
                               FontSize="12" TextColor="Gray" Margin="10,0,0,0"/>
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </VerticalStackLayout>
</ContentPage>
using Microsoft.Maui.Controls;
using System;
using System.Collections.ObjectModel;
using ToDoList.Models;
using ToDoList.Services;

namespace ToDoList
{
    public partial class MainPage : ContentPage
    {
        private readonly MongoDbService _mongoDbService = new();
        private ObservableCollection<TodoItem> _tasks = new();

        public MainPage()
        {
            InitializeComponent();
            TaskCollectionView.ItemsSource = _tasks;
            LoadTasks();
        }

        private async void LoadTasks()
        {
            try
            {
                var result = await _mongoDbService.GetTodoItemsAsync();
                _tasks.Clear();
                foreach (var item in result)
                    _tasks.Add(item);
            }
            catch (Exception ex)
            {
                await DisplayAlert("エラー", $"タスク取得失敗: {ex.Message}", "OK");
            }
        }
    }
}

🔐 接続文字列に関する注意

MongoDbService.cs に記述する MongoDB の接続文字列(connectionUri)には 認証情報が含まれます。GitHubなどの公開リポジトリにアップロードする際は、環境変数やSecrets Managerを利用することを強くおすすめします。


📚 モデルとコレクションの名前一致について

MongoDBのコレクション名 "tasks" は、C#側の TodoItem クラスの用途と一致しています。
フィールド名(title, dueDate, isCompleted など)はMongoDB上のフィールドと一致する必要があります。


🧩 MainPage.xaml とコードビハインドの連携について

XAML ファイルに記述されている以下の行は、C#コードと密接に関係しています:

x:Class="ToDoList.MainPage"

これは MainPage.xaml.cs のクラス定義 namespace ToDoList 内の public partial class MainPage に対応しています。

また、x:Name="TaskCollectionView" は、コードビハインドで直接バインド処理に使用されます。


🖥 実行結果について

以下のように MongoDB から取得したタスクの一覧が表示されていれば成功です:

image.png


おわりに

今回は、MongoDB Atlas からタスクデータを取得し、.NET MAUIアプリ上で一覧表示するまでの流れを解説しました。

次回は、新しいタスクの登録機能や、タスク削除機能の実装に進む予定です。

.NET MAUIとMongoDBを組み合わせたモバイルアプリ開発に興味のある方は、ぜひ引き続きご覧ください!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?