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

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

2024.04.20
XML
カテゴリ: C#.NET


C#のWPFアプリケーションでMVVM(Model-View-ViewModel)パターンを使用する基本的なサンプルコードを示します。MVVMは、データのロジックとビュー(表示)の分離を促進し、アプリケーションの保守性やテスト容易性を向上させます。


まず、ViewModelクラスを定義します。


```csharp

using System.ComponentModel;

using System.Runtime.CompilerServices;


namespace MVVMExample

{

    public class MainViewModel : INotifyPropertyChanged

    {

        private string _displayText;


        public event PropertyChangedEventHandler PropertyChanged;


        public MainViewModel()

        {

            // 初期化

            DisplayText = "Hello, MVVM!";

        }


        public string DisplayText

        {

            get { return _displayText; }

            set

            {

                if (_displayText != value)

                {

                    _displayText = value;

                    OnPropertyChanged();

                }

            }

        }


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

        {

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

        }

    }

}

```


次に、View(表示)のXAMLを定義します。


```xml

<Window x:Class="MVVMExample.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:MVVMExample"

        mc:Ignorable="d"

        Title="MVVM Example" Height="150" Width="300">

    <Grid>

        <StackPanel Margin="10">

            <TextBlock Text="{Binding DisplayText}" FontSize="20" HorizontalAlignment="Center"/>

            <Button Content="Change Text" Command="{Binding ChangeTextCommand}" HorizontalAlignment="Center" Margin="10"/>

        </StackPanel>

    </Grid>

</Window>

```


最後に、ViewとViewModelを接続します。MainWindow.xaml.csファイルに以下のコードを追加します。


```csharp

using System.Windows;


namespace MVVMExample

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

            DataContext = new MainViewModel();

        }

    }

}

```


このサンプルでは、ViewModelが表示用のテキストを保持し、Viewがそのテキストを表示します。また、ボタンをクリックすると、ViewModelのプロパティが変更され、Viewに反映されます。MVVMパターンを使用することで、ビューとロジックの疎結合が実現され、テストや保守が容易になります。






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

Last updated  2024.04.20 14:16:17


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

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