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

エッセンシャルWPF:Windows Presentation Foundation (Programmer's SELECTION)
- 作者: Chris Anderson,星睦
- 出版社/メーカー: 翔泳社
- 発売日: 2007/10/31
- メディア: 大型本
- 購入: 6人 クリック: 128回
- この商品を含むブログ (32件) を見る
1. はじめに
こんにちは、iOSのエディタアプリPWEditorの開発者の二俣です。
今回は業務で使用しているWPFのDataGridに任意のクラスを設定する方法についてです。
2. WPFのDataGridに任意のクラスを設定する
WPFのDataGridに任意のクラスを設定する方法ですが、以下のような実装になります。
設定したクラスはDataGridのDataContextとして取得できます。
実葬例
MainWindow.xaml
<Window x:Class="WPFDataGridContent.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:WPFDataGridContent" 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 WPFDataGridContent { /** * @brief セルデータクラス * ユーザが定義するクラス */ class CellData { // NameがDataGridのセルに表示されます。 public string Name { get; set; } public string Data1 { get; set; } public string Data2 { get; set; } public override string ToString() { return Name; } } /** * @brief セルアイテムクラス * DataGridに設定するクラス */ class CellItem { public CellData CellData { get; set; } } /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { /** * @brief コンストラクタ */ public MainWindow() { InitializeComponent(); // DataGridにデータを設定します。 var items = new List<CellItem>(); items.Add(new CellItem() { CellData = new CellData() { Name = "セルデータ1", Data1 = "データ11", Data2 = "データ12" } } ); items.Add(new CellItem() { CellData = new CellData() { Name = "セルデータ2", Data1 = "データ21", Data2 = "データ22" } }); items.Add(new CellItem() { CellData = new CellData() { Name = "セルデータ3", Data1 = "データ31", Data2 = "データ32" } }); dataGrid.ItemsSource = items; } /** * @brief ウィンドウが描画された後に呼び出されます。 * * @param [in] sender ウィンドウ * @param [in] e イベント */ private void Window_ContentRendered(object sender, EventArgs e) { // 行0, 列0のDataGridCellを取得します。 var cell = GetDataGridCell(dataGrid, 0, 0); // DataGridCellのDataContextを取得します。 // DataContextにCellItem型のオブジェクトが設定されています。 var cellItem = cell.DataContext as CellItem; // 以下、CellItem型のオブジェクトとして処理します。 Console.WriteLine(cellItem); } // 内部メソッド(詳細は省略) 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のセルに表示データ以外の付加情報を持たせる必要がありました。
最初、付加情報はDataGridと同じ行/列数の2次元配列で管理することも考えましたが、煩雑になるためやめました。
次にDataGridのタグに設定することも考えましたが、表示データは付加情報から組み立てるため、こちらも断念しました。
最終的に上記の形に落ち着きました。

実戦で役立つ C#プログラミングのイディオム/定石&パターン
- 作者: 出井秀行
- 出版社/メーカー: 技術評論社
- 発売日: 2017/02/18
- メディア: 大型本
- この商品を含むブログ (1件) を見る
紹介している一部の記事のコードはGitlabで公開しています。
興味のある方は覗いてみてください。
私が勤務しているニューラルでは、主に組み込み系ソフトの開発を行っております。
弊社製品のハイブリッドOS Bi-OSは高い技術力を評価されており、特に制御系や通信系を得意としています。
私自身はiOSモバイルアプリやウィンドウズアプリを得意としております。
ソフトウェア開発に関して相談などございましたら、お気軽にご連絡ください。
また一緒に働きたい技術者の方も随時募集中です。
興味がありましたらご連絡ください。
EMAIL : info-nr@newral.co.jp / m-futamata@newral.co.jp
TEL : 042-523-3663
FAX : 042-540-1688