「東雲 忠太郎」の平凡な日常のできごと

「東雲 忠太郎」の平凡な日常のできごと

2024.05.29
XML
カテゴリ: C#.NET


C# WPFのMVVMパターンは、アプリケーションのUIとビジネスロジックを分離し、テスト可能性と再利用性を向上させるためのアーキテクチャです。以下に、シンプルなMVVMパターンのサンプルコードを示します。


### 1. Model




```csharp

public class Person

{

    public string FirstName { get; set; }

    public string LastName { get; set; }

}

```


### 2. ViewModel


ViewModelは、ModelとViewの間の仲介役を務めます。プロパティやコマンドを公開して、バインディング可能にします。


```csharp

using System.ComponentModel;

using System.Runtime.CompilerServices;

using System.Windows.Input;


public class PersonViewModel : INotifyPropertyChanged

{

    private Person _person;

    public Person Person

    {

        get => _person;

        set

        {

            _person = value;

            OnPropertyChanged();

        }

    }


    public string FullName => $"{Person.FirstName} {Person.LastName}";


    public ICommand UpdateCommand { get; }


    public PersonViewModel()

    {

        Person = new Person { FirstName = "John", LastName = "Doe" };

        UpdateCommand = new RelayCommand(UpdatePerson);

    }


    private void UpdatePerson()

    {

        Person.FirstName = "Jane";

        Person.LastName = "Smith";

        OnPropertyChanged(nameof(FullName));

    }


    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)

    {

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

    }

}


public class RelayCommand : ICommand

{

    private readonly Action _execute;

    private readonly Func<bool> _canExecute;


    public RelayCommand(Action execute, Func<bool> canExecute = null)

    {

        _execute = execute;

        _canExecute = canExecute;

    }


    public bool CanExecute(object parameter) => _canExecute?.Invoke() ?? true;

    public void Execute(object parameter) => _execute();


    public event EventHandler CanExecuteChanged

    {

        add => CommandManager.RequerySuggested += value;

        remove => CommandManager.RequerySuggested -= value;

    }

}

```


### 3. View (XAML)


Viewは、ユーザーインターフェイスを定義し、ViewModelのプロパティにバインドします。


```xml

<Window x:Class="MVVMSample.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MVVM Sample" Height="200" Width="400">

    <Window.DataContext>

        <local:PersonViewModel/>

    </Window.DataContext>

    <Grid>

        <StackPanel>

            <TextBlock Text="{Binding FullName}" FontSize="24" HorizontalAlignment="Center"/>

            <Button Content="Update" Command="{Binding UpdateCommand}" HorizontalAlignment="Center"/>

        </StackPanel>

    </Grid>

</Window>

```


### 4. MainWindow Code-Behind


`MainWindow.xaml.cs`は通常、ViewModelをインスタンス化してDataContextに設定するために使用されます。


```csharp

using System.Windows;


namespace MVVMSample

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

        }

    }

}

```


### プロジェクト構成


```

MVVMSample

├── Model

│   └── Person.cs

├── ViewModel

│   └── PersonViewModel.cs

│   └── RelayCommand.cs

├── View

│   └── MainWindow.xaml

│   └── MainWindow.xaml.cs

```


このシンプルなサンプルでは、`Person`モデルを使って、ViewModelの`PersonViewModel`がプロパティ変更を通知し、Viewでそれをバインドして表示する仕組みを実装しています。また、`RelayCommand`クラスを使用して、ボタンのクリックイベントをViewModelにバインドしています。






お気に入りの記事を「いいね!」で応援しよう

Last updated  2024.05.29 03:20:04


【毎日開催】
15記事にいいね!で1ポイント
10秒滞在
いいね! -- / --
おめでとうございます!
ミッションを達成しました。
※「ポイントを獲得する」ボタンを押すと広告が表示されます。
x

© Rakuten Group, Inc.
X
Design a Mobile Site
スマートフォン版を閲覧 | PC版を閲覧
Share by: