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

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

2024.06.09
XML
カテゴリ: WPFC#.NET


C# WPFのMVVMパターンで、`CommandParameter`に複数のパラメータを渡す方法を示します。複数のパラメータを渡すためには、オブジェクトの配列やタプルなどを使用して一つのオブジェクトとして渡すことが一般的です。ここでは、タプルを使用して複数のパラメータを渡す例を示します。


### 1. RelayCommand クラスの作成




**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);

        }

    }

}

```


### 2. ViewModel の作成


次に、コマンドを定義し、パラメータを処理する ViewModel を作成します。


**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)

        {

            if (parameter is Tuple<string, string> parameters)

            {

                string text1 = parameters.Item1;

                string text2 = parameters.Item2;

                MessageBox.Show($"Text1: {text1}\nText2: {text2}");

            }

        }

    }

}

```


### 3. 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>

        <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">

            <TextBox x:Name="textBox1" Width="200" Margin="10"/>

            <TextBox x:Name="textBox2" Width="200" Margin="10"/>

            <Button Content="Show Message" Width="200" Command="{Binding ShowMessageCommand}">

                <Button.CommandParameter>

                    <MultiBinding Converter="{StaticResource MultiValueConverter}">

                        <Binding ElementName="textBox1" Path="Text" />

                        <Binding ElementName="textBox2" Path="Text" />

                    </MultiBinding>

                </Button.CommandParameter>

            </Button>

        </StackPanel>

    </Grid>

</Window>

```


### 4. MultiValueConverter の作成


複数のバインディングを一つのコマンドパラメータに変換するために、`IMultiValueConverter` を実装します。


**MultiValueConverter.cs**

```csharp

using System;

using System.Globalization;

using System.Windows.Data;


namespace WpfApp

{

    public class MultiValueConverter : IMultiValueConverter

    {

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)

        {

            if (values.Length == 2)

            {

                return Tuple.Create(values[0]?.ToString(), values[1]?.ToString());

            }

            return null;

        }


        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)

        {

            throw new NotImplementedException();

        }

    }

}

```


### 5. Resources の設定


MultiValueConverter をリソースとして追加します。


**App.xaml**

```xml

<Application x:Class="WpfApp.App"

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

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

             StartupUri="MainWindow.xaml">

    <Application.Resources>

        <local:MultiValueConverter x:Key="MultiValueConverter" />

    </Application.Resources>

</Application>

```


### 6. Code-Behind の設定


MainWindow.xaml.csで、データコンテキストを ViewModel に設定します。


**MainWindow.xaml.cs**

```csharp

using System.Windows;


namespace WpfApp

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

            DataContext = new MainViewModel();

        }

    }

}

```


### 説明


1. **RelayCommand.cs**:

   - `RelayCommand` クラスは `ICommand` インターフェースを実装し、コマンドの実行ロジック (`execute`) と実行可能かどうかを決定するロジック (`canExecute`) を受け取ります。


2. **MainViewModel.cs**:

   - `MainViewModel` クラスは、ViewModelとして機能し、`ShowMessageCommand`というコマンドを公開します。コマンドが実行されると、`ShowMessage`メソッドが呼び出され、パラメータとしてタプルが渡されます。


3. **MultiValueConverter.cs**:

   - `MultiValueConverter` クラスは、複数のバインディング値を一つのコマンドパラメータに変換します。この例では、2つのTextBoxのテキストをタプルに変換しています。


4. **MainWindow.xaml**:

   - `MultiBinding` を使用して、2つのTextBoxのテキストをタプルに変換し、ボタンの `CommandParameter` に渡しています。


5. **App.xaml**:

   - `MultiValueConverter` をアプリケーションリソースとして登録しています。


6. **MainWindow.xaml.cs**:

   - `MainWindow` のコンストラクタで、データコンテキストを `MainViewModel` のインスタンスに設定しています。


この構成により、複数のパラメータをコマンドに渡し、処理することができます。






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

Last updated  2024.06.09 13:26:50


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

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