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

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

2024.06.09
XML
カテゴリ: WPFC#.NET


WPFで`CommandParameter`を使用して複数のパラメータを渡すには、通常、タプルや配列、またはカスタムクラスを使用します。ここでは、`CommandParameter`を使用して複数のパラメータを渡す方法とそのサンプルコードを示します。


### タプルを使用した例




まず、コマンドを定義するための `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をデータコンテキストとしてバインドし、複数のパラメータを一つの `CommandParameter` として渡します。


**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" Click="OnButtonClick"/>

        </StackPanel>

    </Grid>

</Window>

```


#### 4. Code-Behind の設定


コードビハインドで、ボタンのクリックイベントでコマンドを実行し、パラメータを渡します。


**MainWindow.xaml.cs**

```csharp

using System;

using System.Windows;


namespace WpfApp

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

            DataContext = new MainViewModel();

        }


        private void OnButtonClick(object sender, RoutedEventArgs e)

        {

            var viewModel = DataContext as MainViewModel;

            if (viewModel != null)

            {

                string text1 = textBox1.Text;

                string text2 = textBox2.Text;

                var parameters = Tuple.Create(text1, text2);

                viewModel.ShowMessageCommand.Execute(parameters);

            }

        }

    }

}

```


### 説明


1. **RelayCommand.cs**:

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


2. **MainViewModel.cs**:

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


3. **MainWindow.xaml**:

   - `TextBox`の値を入力するUIを作成し、ボタンのクリックイベントをハンドルします。


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

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

   - `OnButtonClick` メソッドで、`TextBox` の値を取得し、タプルとしてコマンドに渡します。


### その他の方法


もし、タプルを使わずに複数のパラメータを渡したい場合、以下のように配列やカスタムクラスを使うこともできます。


#### 配列を使用する例


**MainViewModel.cs**

```csharp

private void ShowMessage(object parameter)

{

    if (parameter is object[] parameters && parameters.Length == 2)

    {

        string text1 = parameters[0] as string;

        string text2 = parameters[1] as string;

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

    }

}

```


**MainWindow.xaml.cs**

```csharp

private void OnButtonClick(object sender, RoutedEventArgs e)

{

    var viewModel = DataContext as MainViewModel;

    if (viewModel != null)

    {

        string text1 = textBox1.Text;

        string text2 = textBox2.Text;

        var parameters = new object[] { text1, text2 };

        viewModel.ShowMessageCommand.Execute(parameters);

    }

}

```


#### カスタムクラスを使用する例


**Parameters.cs**

```csharp

public class Parameters

{

    public string Text1 { get; set; }

    public string Text2 { get; set; }

}

```


**MainViewModel.cs**

```csharp

private void ShowMessage(object parameter)

{

    if (parameter is Parameters parameters)

    {

        string text1 = parameters.Text1;

        string text2 = parameters.Text2;

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

    }

}

```


**MainWindow.xaml.cs**

```csharp

private void OnButtonClick(object sender, RoutedEventArgs e)

{

    var viewModel = DataContext as MainViewModel;

    if (viewModel != null)

    {

        string text1 = textBox1.Text;

        string text2 = textBox2.Text;

        var parameters = new Parameters { Text1 = text1, Text2 = text2 };

        viewModel.ShowMessageCommand.Execute(parameters);

    }

}

```


これらの方法を使うことで、複数のパラメータをコマンドに渡して処理することができます。






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

Last updated  2024.06.09 13:31:46


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

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