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

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

2024.04.20
XML
カテゴリ: C#.NET


MVVM (Model-View-ViewModel) パターンを使用した C# WPF のサンプルコードを以下に示します。


まず、ViewModel を定義します。



using System.ComponentModel;


namespace YourNamespace

{

    public class MainViewModel : INotifyPropertyChanged

    {

        private string _displayText;


        public string DisplayText

        {

            get { return _displayText; }

            set

            {

                if (_displayText != value)

                {

                    _displayText = value;

                    OnPropertyChanged("DisplayText");

                }

            }

        }


        public MainViewModel()

        {

            DisplayText = "Hello, MVVM!";

        }


        public event PropertyChangedEventHandler PropertyChanged;


        protected virtual void OnPropertyChanged(string propertyName)

        {

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

        }

    }

}

```


次に、View を作成します。


```xml

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

        DataContext="{Binding MainViewModel, Source={StaticResource Locator}}">

    <Grid>

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

    </Grid>

</Window>

```


最後に、ViewModel をローカライズします。


```csharp

using GalaSoft.MvvmLight.Ioc;

using GalaSoft.MvvmLight;


namespace YourNamespace

{

    public class ViewModelLocator

    {

        static ViewModelLocator()

        {

            SimpleIoc.Default.Register<MainViewModel>();

        }


        public MainViewModel MainViewModel

        {

            get { return ServiceLocator.Current.GetInstance<MainViewModel>(); }

        }

    }

}

```


これは、非常に基本的な MVVM のサンプルです。ViewModel がビューにデータを提供し、ビューが ViewModel によって変更を通知するように構成されています。ビューモデルのインスタンスは、ViewModelLocator を使用してビューに注入されます。






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

Last updated  2024.04.20 14:14:01


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

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