In the previous article "WPF 4 DataGrid Control (custom style)", we learned the custom style methods related to the DataGrid list header, row header, row, and cell, in this article, we continue to make some advanced settings for custom styles.
DataGridTemplateColumn class
In addition to the column types shown in the following table, you can also use the DataGridTemplateColumn Custom column style to add a more perfect data display mode for the DataGrid.
First, we add ExamDate to the class to display the student test date in the DataGrid and assign values to the corresponding student.
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; }}
… …
ObservableCollection<Member> memberData = new ObservableCollection<Member>();… …memberData.Add(new Member(){ Name = "Lucy", Age = "25", Sex = SexOpt.Female, Pass = true, ExamDate = new DateTime(2010, 4, 10), Email = new Uri("mailto:Lucy@school.com")});dataGrid.DataContext = memberData;
… …
The following code defines two ememplate style templates in <Window. Resources>. The first one is used to set the display mode of the date column:
<DataTemplate x:Key="DateTemplate" > <StackPanel Width="40" Height="30"> <Border Background="Orange" BorderBrush="Black" BorderThickness="1"> <TextBlock Text="{Binding ExamDate, StringFormat={}{0:MM-dd}}" FontSize="10" HorizontalAlignment="Center"/> </Border> <Border Background="White" BorderBrush="Black" BorderThickness="1"> <TextBlock Text="{Binding ExamDate, StringFormat={}{0:yyyy}}" FontSize="10" HorizontalAlignment="Center"/> </Border> </StackPanel></DataTemplate>
The second is used to set the editing method of the date column. DataPicker is used here:
<DataTemplate x:Key="EditingDateTemplate"> <DatePicker SelectedDate="{Binding ExamDate}"/></DataTemplate>
After the template is set, you must add the DataGridTemplateColumn in <DataGrid> to display the student's test date.
... ...<DataGridTemplateColumn Header="Exam Date" CellTemplate="{StaticResource DateTemplate}" CellEditingTemplate="{StaticResource EditingDateTemplate}"/>... ...
After setting the CellTemplate and CellEditingTemplate attributes in the XAML code, you can run the program to test the effect.
As shown in, if you modify the Exam Date column, its display mode will change to DataPicker, and you can easily select the corresponding Date for modification.
After modification, restore to original state: