DataGrid コントロールの行ヘッダに行番号を表示する
DataGrid コントロールによって表形式でデータを表示したとき、その行ヘッダに行番号を入れたい場合は多々あります。このような機能は使い回しが効くように、添付ビヘイビアで作成しておくと便利です。
MainViewModel クラスと MainView を次のように定義します。
namespace Tips_DataGrid1.ViewModels
{
using System.Collections.ObjectModel;
using System.Linq;
using Tips_DataGrid1.Models;
public class MainViewModel : NotificationObject
{
public MainViewModel()
{
this.People = new ObservableCollection<Person>(Enumerable.Range(0, 10).Select(x => new Person()
{
Name = "田中 " + x + "太郎",
Age = x,
Gender = x % 3 != 0 ? Gender.Male : Gender.Female,
IsAuthenticated = x % 4 != 0,
}));
}
private ObservableCollection<Person> _people;
/// <summary>
/// 人物データコレクションを取得します。
/// </summary>
public ObservableCollection<Person> People
{
get { return this._people; }
private set { SetProperty(ref this._people, value); }
}
}
}
<Window x:Class="Tips_DataGrid1.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainView"
Height="300" Width="300"
WindowStartupLocation="CenterScreen">
<DataGrid ItemsSource="{Binding People}" />
</Window>
DataGrid コントロールによって People プロパティの持つ人物データコレクションが表形式で表示されることになります。ここまでのコードによる実行結果は下図のようになります。
ここで、次のような添付ビヘイビアを定義します。添付ビヘイビアに関しては 添付ビヘイビアを作成する を参照してください。
namespace Tips_DataGrid1.Views.Behaviors
{
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
/// <summary>
/// <c>System.Windows.Controls.DataGrid</c> コントロールに関する添付ビヘイビアを表します。
/// </summary>
public class DataGridBehavior
{
#region DisplayRowNumber 添付プロパティ
/// <summary>
/// DisplayRowNumber 添付プロパティの定義
/// </summary>
public static DependencyProperty DisplayRowNumberProperty = DependencyProperty.RegisterAttached("DisplayRowNumber", typeof(int?), typeof(DataGridBehavior), new FrameworkPropertyMetadata(null, OnDisplayRowNumberChanged));
/// <summary>
/// DisplayRowNumber 添付プロパティを取得します。
/// </summary>
/// <param name="target">対象とする DependencyObject を指定します。</param>
/// <returns>取得した値を返します。</returns>
public static int? GetDisplayRowNumber(DependencyObject target)
{
return (int?)target.GetValue(DisplayRowNumberProperty);
}
/// <summary>
/// DisplayRowNumber 添付プロパティを設定します。
/// </summary>
/// <param name="target">対象とする DependencyObject を指定します。</param>
/// <param name="value">設定値を指定します。</param>
public static void SetDisplayRowNumber(DependencyObject target, int? value)
{
target.SetValue(DisplayRowNumberProperty, value);
}
/// <summary>
/// DisplayRowNumber 添付プロパティ変更イベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private static void OnDisplayRowNumberChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var dataGrid = sender as DataGrid;
if (dataGrid == null)
return;
if (e.NewValue != null)
{
var displayNumber = GetDisplayRowNumber(dataGrid);
EventHandler<DataGridRowEventArgs> loadedRowHandler = null;
loadedRowHandler = (object _, DataGridRowEventArgs ea) =>
{
if (displayNumber == null)
{
dataGrid.LoadingRow -= loadedRowHandler;
return;
}
ea.Row.Header = ea.Row.GetIndex() + displayNumber;
};
dataGrid.LoadingRow += loadedRowHandler;
ItemsChangedEventHandler itemsChangedHandler = null;
itemsChangedHandler = (object _, ItemsChangedEventArgs ea) =>
{
if (displayNumber == null)
{
dataGrid.ItemContainerGenerator.ItemsChanged -= itemsChangedHandler;
return;
}
// 子要素の DataGridRow クラスに対してのみヘッダ情報を書き換える
GetVisualChildCollection<DataGridRow>(dataGrid).
ForEach(d => d.Header = d.GetIndex() + displayNumber);
};
dataGrid.ItemContainerGenerator.ItemsChanged += itemsChangedHandler;
}
}
#endregion DisplayRowNumber 添付プロパティ
/// <summary>
/// 指定された型の子要素をリストとして取得します。
/// </summary>
/// <typeparam name="T">リストアップする型を指定します。</typeparam>
/// <param name="parent">子要素を持つ親を指定します。</param>
/// <returns>指定された型の子要素のみを集めたリストを返します。</returns>
private static List<T> GetVisualChildCollection<T>(object parent)
where T : Visual
{
var visualCollection = new List<T>();
GetVisualChildCollection(parent as DependencyObject, visualCollection);
return visualCollection;
}
/// <summary>
/// 指定された型の子要素を与えられたリストに追加します。
/// </summary>
/// <typeparam name="T">リストアップする型を指定します。</typeparam>
/// <param name="parent">子要素を持つ親を指定します。</param>
/// <param name="visualCollection">リストアップするためのリストを指定します。</param>
private static void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection)
where T : Visual
{
int count = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < count; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
if (child is T)
{
visualCollection.Add(child as T);
}
if (child != null)
{
GetVisualChildCollection(child, visualCollection);
}
}
}
}
}
非常に長いですが、DisplayRowNumber という名前の添付プロパティを持っており、このプロパティに指定された数値を始めとして行ヘッダをナンバリングするようにしています。
DataGrid コントロールは各行を DataGridRow コントロールをコンテナとして表現しています。したがって、上記の添付ビヘイビアの中では、DataGrid が持つ DataGridRow コントロールを抽出し、それぞれの DataGridRow.Header プロパティにアクセスして行ヘッダを変更しています。
どの DataGridRow コントロールが何番目であるかは DataGridRow クラスが持つ GetIndex() メソッドで取得しています。GetIndex() メソッドは DataGrid コントロールの Items プロパティを参照して何番目かを取得しているため、列ヘッダをクリックすることなどによるソーティングがおこなわれたとしても、一行目は必ず 0 となります。
上記のコードでは、DisplayRowNumber 添付プロパティを基準として行番号を振っているため、任意の数値から開始させることができます。
この添付ビヘイビアの使用例は次のようになります。
<Window x:Class="Tips_DataGrid1.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="clr-namespace:Tips_DataGrid1.Views.Behaviors"
Title="MainView"
Height="300" Width="300"
WindowStartupLocation="CenterScreen">
<DataGrid ItemsSource="{Binding People}" b:DataGridBehavior.DisplayRowNumber="1" />
</Window>
添付ビヘイビアを使用するために名前空間 "b" の定義を追加しています。後は通常の添付プロパティを設定する要領で DataGrid コントロールに DisplayRowNumber 添付プロパティを記述します。
このコードの実行結果は次のようになります。DisplayRowNumber 添付プロパティに 1 を指定したため、行番号は 1 から始まっています。また、あくまでも行番号であるため、列をソートしたとしても、この番号は変わらず 1 から順に表示されるようになります。
Tweet