C#プログラミング

【C#】DataGridでコンボボックスとチェックボックスを使う方法【WPF/MVVM】

データグリッドでコンボボックスチェックボックスを用いる方法記事のアイキャッチ画像 C#

本記事ではDataGridにてコンボボックス(ComboBox)とチェックボックス(CheckBox)を表示する方法をサンプルコードで紹介します。複数のデータを編集する際の設定操作や、複数のチャンネルを持つ機器を操作する場合の設定をする際に便利です。

スポンサーリンク

DataGridの基本的な使い方

以下記事で紹介しています。もしDataGridをまだ使用したことがない方はまず以下記事を見ることをお勧めします。本記事はその応用編に当たります。

スポンサーリンク

DataGridにコンボボックス、チェックボックスを表示させる方法

数値(intなど)や文字列(string)をDataGridに表示させる場合は、それらを要素として持つコレクションとView側DataGridをバインドさせればできます(過去記事参照)。

コンボボックスやチェックボックスといった機能を持つものを表示させるためにView側で何か工夫がいるのかな?と思うかもしれませんが、実はいりません。

ここではViewModel側コレクション内要素の型が重要です。

コンボボックスの場合はenum型チェックボックスの場合はbool型の要素を持つコレクションとDataGridをバインドすれば実装できます。

スポンサーリンク

サンプルコード(MVVM)

以下のようなサンプルを作成しました。
一番上には動作確認用のボタンがあります。

サンプルアプリ起動時の様子

動作確認用のボタンを押すと、VisualStudioの出力画面に以下のような出力が表示されます。

動作確認ボタンを押した際の出力内容

DataGridを編集しても、ちゃんと出力内容も変化していることが確認できます。

View

XAMLは以下の通り。DataGridとコレクションをバインドするだけ。コレクションの要素の型に応じて勝手にコンボボックスやチェックボックスになります。

<Window x:Class="DatagridSample.Views.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"
        mc:Ignorable="d"
        Title="DatagridSample" Height="300" Width="300">
    <Grid>
        <StackPanel Orientation="Vertical" >
            <Button Content="Button1(動作確認用)" Command="{Binding Button1_Pushed}" />
            <!--データグリッド-->
            <DataGrid Margin="10" ItemsSource="{Binding ElementsCollection}"/>
        </StackPanel>
    </Grid>
</Window>

コードビハインドは以下の通り。いつものです。

using DatagridSample.ViewModels;
using System.Windows;

namespace DatagridSample.Views
{
    public partial class MainWindow : Window
    {
        MainViewModel vm = new MainViewModel();
        
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = vm;
        }
    }
}

ViewModel

以下の通り。

using DatagridSample.Common;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;

namespace DatagridSample.ViewModels
{
    internal class MainViewModel : INotifyPropertyChanged
    {
        //DataGridとバインドするコレクション
        public Collection<Elements> ElementsCollection { get; set; }

        //動作確認用コマンド
        public ICommand Button1_Pushed { get; set; }


        public MainViewModel()
        {
            //コマンド
            Button1_Pushed = new RelayCommand(Button1_Command);

            //名前・タイプリスト
            string[] names = new string[3] { "Sato", "Matsui", "Suzuki" };
            
            //表示用のコレクション作成
            ElementsCollection = new Collection<Elements>();

            //ループで要素作成
            for (int i=0; i < 3; i++)
            {
                //DataGrid上1行分の要素作成
                Elements one = new Elements()
                {
                    num = i + 1,
                    name = names[i],
                    types = (TypesEnum)1,
                    state = true
                };
                //コレクションに要素を追加
                ElementsCollection.Add(one);
            }
        }

        //コマンド(動作確認用)
        private void Button1_Command()
        {
            //コレクション要素出力用
            for(int i = 0; i < ElementsCollection.Count; i++)
            {
                Console.WriteLine("◆{0}行目要素:{1}、{2}、{3}、{4}", i, ElementsCollection[i].num, ElementsCollection[i].name,ElementsCollection[i].types, ElementsCollection[i].state);
            }
        }

        //変数の更新通知用
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }

    //コレクション内要素
    class Elements
    {
        public int num { get; set; }
        public string name { get; set; }
        //DataGrid内コンボボックス用
        public TypesEnum types { get; set; }
        //DataGrid内チェックボックス用
        public bool state { get; set; }
    }

    //DataGrid内コンボボックス要素
    public enum TypesEnum
    {
        Type_A = 1,
        Type_B = 2,
        Type_C = 3
    }
}

Modelは関係ないので省略。
以上。

GUI関連でラジオボタンの使い方の紹介もしています↓

コメント

タイトルとURLをコピーしました