プログラムを書こう!

実務や自作アプリ開発で習得した役に立つソフトウェア技術情報を発信するブログ

WPFのDataGridでセルの背景色を変更する。

この記事は2019年05月27日に投稿しました。

f:id:paveway:20190914064630j:plain

目次

  1. はじめに
  2. WPFのDataGridでセルの背景色を変更する
  3. おわりに

エッセンシャルWPF:Windows Presentation Foundation (Programmer's SELECTION)

エッセンシャルWPF:Windows Presentation Foundation (Programmer's SELECTION)

1. はじめに

こんにちは、iOSのエディタアプリPWEditorの開発者の二俣です。
今回は業務で使用しているWPFDataGridでセルの背景色を変更する方法についてです。

目次へ

2. WPFのDataGridでセルの背景色を変更する

WPFDataGridでセルの背景色を変更する方法ですが、セルに設定されるコントロールのBackgroundプロパティに背景色を設定して行います。

実装例では、データのあるセルの背景色を緑色に変更しています。

実葬例

MainWindow.xaml

<Window x:Class="WPFDataGridBackground.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"
        xmlns:local="clr-namespace:WPFDataGridBackground"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" ContentRendered="Window_ContentRendered">
    <Grid>
        <DataGrid Name="dataGrid" />
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFDataGridBackground
{
    class CellData
    {
        public string Data1 { get; set; }
        public string Data2 { get; set; }
        public string Data3 { get; set; }
    }
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        /**
         * @brief コンストラクタ
         */
        public MainWindow()
        {
            InitializeComponent();

            // データグリッドにサンプルデータを設定します。
            var items = new List<CellData>();
            items.Add(new CellData() { Data1 = "Data11", Data2 = "", Data3 = "" });
            items.Add(new CellData() { Data1 = "", Data2 = "Data22", Data3 = "" });
            items.Add(new CellData() { Data1 = "", Data2 = "", Data3 = "Data33" });
            dataGrid.ItemsSource = items;
        }

        /**
         * ウィンドウが描画された後に呼び出されます。
         * 
         * @param [in] sender ウィンドウ
         * @param [in] e イベント
         */
        private void Window_ContentRendered(object sender, EventArgs e)
        {
            // データグリッドのセル数分繰り返します。
            var rowNum = dataGrid.Items.Count;
            var columnNum = dataGrid.Columns.Count;
            for (int i = 0; i < rowNum; ++i)
            {
                for (int j = 0; j < columnNum; ++j)
                {
                    // セルにデータが設定されている場合、背景色をグリーンに変更します。
                    var cell = GetDataGridCell(dataGrid, i, j);
                    var content = cell.Content;
                    var textBlock = content as TextBlock;
                    var text = textBlock.Text;
                    if (string.IsNullOrEmpty(text)) continue;
                    textBlock.Background = Brushes.Green;
                }
            }
        }

        // 内部メソッド(詳細は省略)

        public DataGridCell GetDataGridCell(DataGrid dataGrid, int rowIndex, int columnIndex)
        {
            if (dataGrid.Items == null || dataGrid.Items.IsEmpty)
            {
                return null;
            }

            var row = GetDataGridRow(dataGrid, rowIndex);
            if (row == null)
            {
                return null;
            }

            var presenter = GetVisualChild<DataGridCellsPresenter>(row);
            if (presenter == null)
            {
                return null;
            }

            var generator = presenter.ItemContainerGenerator;
            var cell = generator.ContainerFromIndex(columnIndex) as DataGridCell;
            if (cell == null)
            {
                dataGrid.UpdateLayout();
                var column = dataGrid.Columns[columnIndex];
                dataGrid.ScrollIntoView(row, column);
                cell = generator.ContainerFromIndex(columnIndex) as DataGridCell;
            }
            return cell;
        }

        public DataGridRow GetDataGridRow(DataGrid dataGrid, int index)
        {
            if (dataGrid.Items == null || dataGrid.Items.IsEmpty)
            {
                return null;
            }

            var generator = dataGrid.ItemContainerGenerator;
            var row = generator.ContainerFromIndex(index) as DataGridRow;
            if (row == null)
            {
                dataGrid.UpdateLayout();
                var item = dataGrid.Items[index];
                dataGrid.ScrollIntoView(item);
                row = generator.ContainerFromIndex(index) as DataGridRow;
            }
            return row;
        }

        private T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T result = default(T);
            var count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; ++i)
            {
                var child = VisualTreeHelper.GetChild(parent, i) as Visual;
                result = child as T;
                if (result != null)
                {
                    break;
                }

                result = GetVisualChild<T>(child);
            }
            return result;
        }
    }
}

目次へ

3. おわりに

業務アプリで、DataGridのデータのあるセルをわかりやすくするため、背景色を変更することにしました。
そのためその方法を調査しました。

今のシゴトに飽きちゃった...そんなあなたの見方です!【IT派遣テクノウェイブ】

実戦で役立つ C#プログラミングのイディオム/定石&パターン

実戦で役立つ C#プログラミングのイディオム/定石&パターン

紹介している一部の記事のコードはGitlabで公開しています。
興味のある方は覗いてみてください。

目次へ


私が勤務しているニューラルでは、主に組み込み系ソフトの開発を行っております。
弊社製品のハイブリッドOS Bi-OSは高い技術力を評価されており、特に制御系や通信系を得意としています。
私自身はiOSモバイルアプリウィンドウズアプリを得意としております。
ソフトウェア開発に関して相談などございましたら、お気軽にご連絡ください。

また一緒に働きたい技術者の方も随時募集中です。
興味がありましたらご連絡ください。

EMAIL : info-nr@newral.co.jp / m-futamata@newral.co.jp
TEL : 042-523-3663
FAX : 042-540-1688

目次へ