次のデータグリッドがあります
<DataGrid x:Name="dataGrid1"
AutoGenerateColumns="False"
ItemsSource="{Binding}">
<DataGrid.Resources>
<DataTemplate DataType="{x:Type DataTypes:Foo}" x:Key="dTemp">
<TextBox Background="{Binding BgColor}" Text="{Binding Path=RowId}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type DataTypes:Foo}" x:Key="dTemp2">
<TextBox Background="{Binding BgColor}" Text="{Binding Path=Alias}"/>
</DataTemplate>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn CellTemplate="{StaticResource dTemp}"/>
<DataGridTemplateColumn CellTemplate="{StaticResource dTemp2}"/>
</DataGrid.Columns>
</DataGrid>
コードビハインドには次のものがあります。
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public ObservableCollection<Foo[]> ObservableCollection;
public MainWindow()
{
InitializeComponent();
this.ObservableCollection = new ObservableCollection<Foo[]>();
Foo[] ocoll = new Foo[3];
ocoll[0] = (new Foo(1, "FIRST ARRAY FIRST ROW FIRST COLUMN", Brushes.Aqua));
ocoll[1] = (new Foo(2, "FIRST ARRAY FIRST ROW SECOND COLUMN", Brushes.Red));
ocoll[2] = (new Foo(3, "FIRST ARRAY FIRST ROW THIRD COLUMN", Brushes.Green));
Foo[] ocoll2 = new Foo[3];
ocoll2[0] = (new Foo(4, "SECOND ARRAY SECOND ROW FIRST COLUMN", Brushes.Aqua));
ocoll2[1] = (new Foo(5, "SECOND ARRAY SECOND ROW SECOND COLUMN", Brushes.Red));
ocoll2[2] = (new Foo(6, "SECOND ARRAY SECOND ROW THIRD COLUMN", Brushes.Green));
this.ObservableCollection.Add(ocoll);
this.ObservableCollection.Add(ocoll2);
dataGrid1.DataContext = ObservableCollection;
}
}
public class Foo
{
public int RowId { get; set; }
public string Alias { get; set; }
public Brush BgColor { get; set; }
public Foo(int rowId, string @alias, Brush bgColor)
{
this.RowId = rowId;
this.Alias = alias;
this.BgColor = bgColor;
}
}
}
オブジェクト Foo には 30 を超えるプロパティがあります (ここでは簡単に理解できるように 2 つだけ書きました)。各 DataGridTemplateColumn の CellTemplate をそれにバインドしますか?