WPF で MVVM Toolkit を利用した場合
Section titled “WPF で MVVM Toolkit を利用した場合”MVVM Toolkit を利用した WPF の MVVM パターンに基づく実装例を示します。
MVVM Toolkit を利用した場合の作成例 (WPF)
Section titled “MVVM Toolkit を利用した場合の作成例 (WPF)”以下のように簡潔に記述するだけで、先ほどの WPF の実装例(自力版) と、まったく同様のことが非常に少ないコード量で実現できます。
プロパティとコマンドの実装 w/ MVVM Toolkit
Section titled “ プロパティとコマンドの実装 w/ MVVM Toolkit”/// <summary>/// メイン画面ビューモデル/// </summary>public sealed partial class MainWindowViewModel : ObservableObject{ /// <summary> /// テキスト /// </summary> [ObservableProperty] public partial string Text { get; set; } = string.Empty;
/// <summary> /// メインコマンド /// </summary> [RelayCommand] private void Main() => Text += '!';
}プロパティとコマンドの使用例 w/ MVVM Toolkit
Section titled “ プロパティとコマンドの使用例 w/ MVVM Toolkit”<Window x:Class="MvvmSelfWpfAppSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 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:local="clr-namespace:MvvmSelfWpfAppSample" mc:Ignorable="d" Title="MainWindow" Height="160" Width="320"> <Window.DataContext> <local:MainWindowViewModel /> </Window.DataContext> <Grid> <Grid.RowDefinitions> <RowDefinition Height="2*"/> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <TextBox Text="{Binding Text, Mode=TwoWay}" Margin="10" Grid.Row="0" /> <Button Content="実行" Command="{Binding MainCommand}" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="1" /> </Grid></Window>/// <summary>/// メイン画面/// </summary>public partial class MainWindow : Window{ public MainWindow() => InitializeComponent();}MVVM Toolkit では、ソースジェネレータによって、必要なコードが自動生成される仕組みとなっています。
そのため、少ないコード量で MVVM パターンを実現することができます。


