Avalonia の Web エクスポート機能を利用して、MVVM パターンと NuGet 生態系を組み合わせた ToDo リストアプリケーションを作成してみます。
まず、デスクトップ版からプロジェクトを作成します。
ToDo リストの MVVM 実装
以下に、シンプルな ToDo リストの MVVM 実装を示します。
TaskItemViewModel の作成
まずは TaskItemViewModel.cs を作成します。
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using System.Windows.Input;
namespace WebApp.ViewModels
{
public partial class TaskItemViewModel : ObservableObject
{
private ObservableCollection<TaskItemViewModel> _collection;
[ObservableProperty]
private string _description;
public ICommand RemoveCommand { get; }
public TaskItemViewModel()
{
RemoveCommand = new RelayCommand(Remove);
}
public TaskItemViewModel(ObservableCollection<TaskItemViewModel> collection) : this()
{
_collection = collection;
}
private void Remove()
{
_collection?.Remove(this);
}
}
}
MainViewModel の作成
次に MainViewModel.cs を作成します。
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using System.Windows.Input;
namespace WebApp.ViewModels
{
public partial class MainViewModel : ObservableObject
{
[ObservableProperty]
private ObservableCollection<TaskItemViewModel> _tasks = new ObservableCollection<TaskItemViewModel>();
[ObservableProperty]
private TaskItemViewModel _selectedTask;
[ObservableProperty]
private string _inputText = "新しいタスク";
public ICommand AddTaskCommand { get; }
public MainViewModel()
{
AddTaskCommand = new RelayCommand(AddTask);
}
private void AddTask()
{
var task = new TaskItemViewModel(Tasks) { Description = InputText };
Tasks.Add(task);
SelectedTask = task;
}
}
}
MainView.xaml の設定
最後に MainView.xaml を以下の内容に変更します。
<UserControl x:Class="WebApp.Views.MainView"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:WebApp.ViewModels"
d:DesignHeight="450"
d:DesignWidth="800"
x:DataType="vm:MainViewModel"
mc:Ignorable="d">
<Design.DataContext>
<vm:MainViewModel />
</Design.DataContext>
<StackPanel>
<ItemsControl ItemsSource="{Binding Tasks}">
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="vm:TaskItemViewModel">
<StackPanel Orientation="Horizontal">
<TextBlock Width="100"
Text="{Binding Description}"
TextTrimming="CharacterEllipsis"
TextWrapping="NoWrap" />
<Button Width="30"
Height="30"
Margin="10,0,0,0"
VerticalAlignment="Center"
Command="{Binding RemoveCommand}"
Content="X" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<StackPanel Orientation="Horizontal">
<TextBox Width="100" Text="{Binding InputText}" />
<Button Command="{Binding AddTaskCommand}" Content="タスク追加" />
</StackPanel>
</StackPanel>
</UserControl>
Web 上での動作確認
ロード中の表示:
ロード完了後の表示: