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

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

2024.06.09
XML
カテゴリ: WPFC#.NET


C# WPFでMVVMパターンを使用して`Command`を実装する方法についてのサンプルコードを示します。MVVM(Model-View-ViewModel)パターンでは、ビュー(XAML)とビューモデル(ViewModel)を分離し、コマンドを使用してユーザーインタラクションを処理します。


以下に示すサンプルコードは、ボタンをクリックしたときにメッセージボックスを表示するシンプルな例です。




まず、コマンドを定義し、ビジネスロジックを処理するViewModelを作成します。


**RelayCommand.cs**

```csharp

using System;

using System.Windows.Input;


namespace WpfApp

{

    public class RelayCommand : ICommand

    {

        private readonly Action<object> execute;

        private readonly Predicate<object> canExecute;


        public event EventHandler CanExecuteChanged

        {

            add { CommandManager.RequerySuggested += value; }

            remove { CommandManager.RequerySuggested -= value; }

        }


        public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)

        {

            this.execute = execute ?? throw new ArgumentNullException(nameof(execute));

            this.canExecute = canExecute;

        }


        public bool CanExecute(object parameter)

        {

            return canExecute == null || canExecute(parameter);

        }


        public void Execute(object parameter)

        {

            execute(parameter);

        }

    }

}

```


**MainViewModel.cs**

```csharp

using System;

using System.Windows;

using System.Windows.Input;


namespace WpfApp

{

    public class MainViewModel

    {

        public ICommand ShowMessageCommand { get; }


        public MainViewModel()

        {

            ShowMessageCommand = new RelayCommand(ShowMessage);

        }


        private void ShowMessage(object parameter)

        {

            MessageBox.Show("Hello, MVVM!");

        }

    }

}

```


### 2. Viewの作成


次に、View(XAML)を作成し、ViewModelをデータコンテキストとしてバインドします。


**MainWindow.xaml**

```xml

<Window x:Class="WpfApp.MainWindow"

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

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

        Title="MainWindow" Height="200" Width="400">

    <Grid>

        <Button Content="Show Message" Command="{Binding ShowMessageCommand}" Width="150" Height="50" HorizontalAlignment="Center" VerticalAlignment="Center"/>

    </Grid>

</Window>

```


**MainWindow.xaml.cs**

```csharp

using System.Windows;


namespace WpfApp

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

            DataContext = new MainViewModel();

        }

    }

}

```


### プロジェクト構成


このプロジェクトは以下のように構成されます。


```

WpfApp

|-- App.xaml

|-- App.xaml.cs

|-- MainWindow.xaml

|-- MainWindow.xaml.cs

|-- RelayCommand.cs

|-- MainViewModel.cs

```


### 説明


1. **RelayCommand.cs**:

   - `RelayCommand`クラスは`ICommand`インターフェースを実装しており、コマンドを定義するために使用されます。このクラスは、コマンドの実行ロジックと実行可能かどうかのロジックを受け取ります。


2. **MainViewModel.cs**:

   - `MainViewModel`クラスは、ViewModelとして機能し、`ShowMessageCommand`というコマンドを公開します。このコマンドは、ボタンがクリックされたときにメッセージボックスを表示するメソッド`ShowMessage`を呼び出します。


3. **MainWindow.xaml**:

   - `Button`の`Command`プロパティに`ShowMessageCommand`をバインドしています。これにより、ボタンがクリックされたときにViewModel内のコマンドが実行されます。


4. **MainWindow.xaml.cs**:

   - `MainWindow`のコンストラクタで、データコンテキストを`MainViewModel`のインスタンスに設定しています。これにより、ビューがViewModelにバインドされます。


この構成により、MVVMパターンを使用して、ユーザーインターフェースとビジネスロジックを分離し、コマンドを使用してユーザーインタラクションを処理することができます。






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

Last updated  2024.06.09 13:13:20


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

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