WPF Datagrid formatting (part 1)
This source code demonstrates the use of a simple DataGrid. You can sort the rows by any column. The Age column is horizontally aligned to the right. The column headers are using a bold font.
The DataGrid element itself is very flexible. You can add all kinds of columns. The most interesting one is DataGridTemplateColumn, which allows you to add any template. The example template only uses a DatePicker, but you could add far more complexity to it.
Set the SortMemberPath to enable sorting, otherwise the DataGrid sorting algorithm cannot know what data to look at. Remember, we are using a template and not a clearly identifiable data type. In today’s example SortMemberPath is set to “Birthday.Day”, which sorts by the day of the month. In case you prefer to sort by date in general, use SortMemberPath=”Birthday” instead.
I changed the selection color, because the dark blue had a low contrast compared to the web-links. This is dealt with by style triggers. The advantage of triggers is that they only override properties temporarily. As soon as the trigger becomes invalid the control element returns to its previous formatting.
<Window x:Class="WpfDatagrid.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Language="en-GB" Loaded="Window_Loaded" Closed="Window_Closed" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style TargetType="{x:Type DataGridColumnHeader}"> <Setter Property="VerticalContentAlignment" Value="Center" /> <Setter Property="SeparatorBrush" Value="WhiteSmoke" /> <Setter Property="FontWeight" Value="Bold" /> <Setter Property="Height" Value="30" /> </Style> <Style x:Key="AlignRight" TargetType="{x:Type TextBlock}"> <Setter Property="HorizontalAlignment" Value="Right" /> </Style> </Window.Resources> <Grid> <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}" CanUserAddRows="False" CanUserReorderColumns="True" CanUserResizeColumns="True" CanUserResizeRows="False" SelectionUnit="Cell" SelectionMode="Extended"> <DataGrid.CellStyle> <Style> <Style.Triggers> <Trigger Property="DataGridCell.IsSelected" Value="True"> <Setter Property="DataGridCell.Background" Value="SteelBlue" /> <Setter Property="DataGridCell.BorderBrush" Value="GreenYellow" /> </Trigger> </Style.Triggers> </Style> </DataGrid.CellStyle> <DataGrid.Columns> <DataGridCheckBoxColumn Header="Alive" Binding="{Binding Alive}" /> <DataGridTextColumn Header="Name" Binding="{Binding FirstName}" /> <DataGridTextColumn Header="LastName" Binding="{Binding LastName}" /> <!--<DataGridTemplateColumn Header="Birthday" SortMemberPath="Birthday">--> <DataGridTemplateColumn Header="Birthday" SortMemberPath="Birthday.Day"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <DatePicker SelectedDate="{Binding Birthday}" BorderThickness="0" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTextColumn Header="Age" Binding="{Binding Age, StringFormat=N2}" ElementStyle="{StaticResource AlignRight}" IsReadOnly="True" /> <DataGridHyperlinkColumn Header="Homepage" Binding="{Binding Homepage}" IsReadOnly="True"> <DataGridHyperlinkColumn.ElementStyle> <Style> <EventSetter Event="Hyperlink.Click" Handler="Hyperlink_Clicked"/> </Style> </DataGridHyperlinkColumn.ElementStyle> </DataGridHyperlinkColumn> </DataGrid.Columns> </DataGrid> </Grid> </Window>
using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows; using System.Windows.Documents; namespace WpfDatagrid { public partial class MainWindow : Window { public class Person { public bool Alive { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime Birthday { get; set; } public double Age { get { return DateTime.Now.Subtract(Birthday).TotalDays / 365; } } public string Homepage { get; set; } } // public MainWindow() { InitializeComponent(); } // private void Window_Loaded(object sender, RoutedEventArgs e) { List<Person> lPersons = new List<Person>(); lPersons.Add(new Person() { FirstName = "Liza", LastName = "Minnelli", Birthday = new DateTime(1946, 03, 12), Alive = true, Homepage = "www.officiallizaminnelli.com" }); lPersons.Add(new Person() { FirstName = "Bastian", LastName = "Ohta", Birthday = new DateTime(1975, 03, 13), Alive = true, Homepage = "www.ohta.de" }); lPersons.Add(new Person() { FirstName = "Albert", LastName = "Einstein", Birthday = new DateTime(1879, 03, 14), Alive = false, Homepage = "www.alberteinsteinsite.com" }); lPersons.Add(new Person() { FirstName = "Coenraad", LastName = "van Houten", Birthday = new DateTime(1801, 03, 15), Alive = false, Homepage = "www.vanhoutendrinks.com" }); lPersons.Add(new Person() { FirstName = "Andrew", LastName = "Miller-Jones", Birthday = new DateTime(1910, 03, 16), Alive = false, Homepage = "dead as a Dodo" }); lPersons.Add(new Person() { FirstName = "Gottlieb", LastName = "Daimler", Birthday = new DateTime(1834, 03, 17), Alive = false, Homepage = "www.daimler.com" }); lPersons.Add(new Person() { FirstName = "Rudolf", LastName = "Diesel", Birthday = new DateTime(1858, 03, 18), Alive = false, Homepage = "http://en.wikipedia.org/wiki/Rudolf_Diesel" }); DataContext = lPersons; } // private void Window_Closed(object sender, EventArgs e) { Application.Current.Shutdown(0); } // private void Hyperlink_Clicked(object sender, RoutedEventArgs e) { try { Hyperlink lHyperlink = e.OriginalSource as Hyperlink; string lUri = lHyperlink.NavigateUri.OriginalString; Process.Start(lUri); } catch (Exception ex) { MessageBox.Show(ex.Message); } } // } // class } // namespace
Posted on April 29, 2014, in Basic, Programming Patterns, WPF and tagged C#, C-sharp, DataGrid, Format, Hyperlink, programming, right alignment, Source code, Style, Template, WPF, XAML. Bookmark the permalink. 1 Comment.
Pingback: WPF Datagrid formatting (part 2, advanced) | C# Hardcore Programming