我有以下数据网格
<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;
}
}
}
Object Foo 有 30 多个属性(我在这里只写了 2 个以便于理解).. 问题是:我真的必须定义 30 个不同的数据模板(如 dTemp、dTemp2、...见上文)来将每个 DataGridTemplateColumn 的 CellTemplate 绑定到它?