上一篇《WPF 4 DataGrid 控件(進階篇一)》中我們通過DataGridTemplateColumn 類自定義編輯了日期列的樣式,當然也可以根據個 人需要設置任何樣式模板。上例中Pass Exam 列顯示學生是否通過考試,但我們並不知道該學生每門學科的成績是多少。本篇將為 DataGrid 行增加這些詳細信息,使得DataGrid 數據更加充實。
首先,我們仍然先更新一下Member 類,增加Math 和History 兩門學科:
public class Member
{
public string Name { get; set; }
public string Age { get; set; }
public SexOpt Sex { get; set; }
public bool Pass { get; set; }
public DateTime ExamDate { get; set; }
public Uri Email { get; set; }
public int Math { get; set; }
public int History { get; set; }
}
為學生賦上考試成績:
… …
memberData.Add(new Member()
{
Name = "Lucy",
Age = "25",
Sex = SexOpt.Female,
Pass = true,
ExamDate = new DateTime(2010, 4, 10),
Email = new Uri("mailto:[email protected]"),
Math = 80,
History = 85
});
dataGrid.DataContext = memberData;
接下來就要到XAML 中為考試成績設計樣式模板:
<Window.Resources>
... ...
<DataTemplate x:Key="RowDetails">
<Border BorderThickness="0" Background="Orchid" Padding="10">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Math: " VerticalAlignment="Center"/>
<TextBlock Text="{Binding Math}" VerticalAlignment="Center"
FontSize="15" FontWeight="Bold"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="History: " VerticalAlignment="Center"/>
<TextBlock Text="{Binding History}" VerticalAlignment="Center"
FontSize="15" FontWeight="Bold"/>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</Window.Resources>
在<DataGrid>中為RowDetailsTemplate 屬性添加RowDetails 模板:
<DataGrid x:Name="dataGrid" ItemsSource="{Binding}"
AutoGenerateColumns="False" SelectionUnit="CellOrRowHeader"
RowDetailsTemplate="{StaticResource RowDetails}">
… …
當然,我們也可以直接在<DataGrid>中添加<DataGrid.RowDetailsTemplate> 完成上面所有XAML 代碼。注:上面代碼中 <DataGrid>的RowDetailsTemplate 屬性要清除。
... ...
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<Border BorderThickness="0" Background="Orchid" Padding="10">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Math: " VerticalAlignment="Center"/>
<TextBlock Text="{Binding Math}" VerticalAlignment="Center"
FontSize="15" FontWeight="Bold"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="History: " VerticalAlignment="Center"/>
<TextBlock Text="{Binding History}" VerticalAlignment="Center"
FontSize="15" FontWeight="Bold"/>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
... ...
編譯程序,點擊行頭顯示詳細考試成績數據。完成這幾篇開發後,我們的DataGrid 內容是不是充實了很多。
源碼:http://cid-c75f4e27adfe5bbc.office.live.com/self.aspx/GnieTech/WPF4DataGridControl.zip