Partilhar via


More fun with DataGrid

Here’s another DataGrid sample using the WPF Toolkit.  It includes

  • Creating templates for DataGridTemplateColumn
  • Binding to DataGridComboBoxColumn
  • Alternating row colors

Here’s an image of what the code looks like running:

DataGridColumnBlog2

To create the Date Published column, I used the DataGridTemplateColumn and bound the CellTemplate to a custom DataTemplate. 

<!--DataTemplate for Published Date column defined in Grid.Resources --> 

<Grid.Resources>

<DataTemplate x:Key="DateTemplate" >

  <StackPanel Width="20" Height="30">

   <Border Background="LightBlue" BorderBrush="Black" BorderThickness="1">

    <TextBlock Text="{Binding PublishDate, StringFormat={}{0:MMM}}" FontSize="8" HorizontalAlignment="Center" />

   </Border>

   <Border Background="White" BorderBrush="Black" BorderThickness="1">

    <TextBlock Text="{Binding PublishDate,StringFormat={}{0:yyyy}}" FontSize="8" HorizontalAlignment="Center" />

   </Border>

  </StackPanel>

</DataTemplate>

...

</Grid.Resources>

 

<!--Define the custom column that shows the published date-->

<toolkit:DataGrid ...>

...

<toolkit:DataGridTemplateColumn Header="Date Published" CellTemplate="{StaticResource DateTemplate}" />

...

<toolkit:DataGrid ...>

It took me a while to figure out how to get binding to the enumeration correct on the CombBoxColumn, but eventually with the help of blog posts from Bea Stollnitz and Vincent Sibal, I was able to put it all together.

<!--Get the values of the MusicCategory enum to populate the ComboBox-->

<Grid.Resources>

...

<ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type core:Enum}" x:Key="myEnum">

   <ObjectDataProvider.MethodParameters>

      <x:Type TypeName="local:MusicCategory" />

   </ObjectDataProvider.MethodParameters>

</ObjectDataProvider>

</Grid.Resources>

 

<!--Define the DataGridComboBoxColumn and bind the ItemsSource and SelectedItem -->

<toolkit:DataGrid ...>

...

<toolkit:DataGridComboBoxColumn Header="Category" SelectedItemBinding="{Binding Category}" ItemsSource="{Binding Source={StaticResource myEnum}}" />

</toolkit:DataGrid ...>

 

Finally the alternating row colors is pretty straight forward but I wanted to show using an AlternationCount of 3.  If you want to get fancy with more colors, check out this blog post from Jaime Rodriguez.  He shows how to use a style with triggers to set the row background based on AlternationIndex in addition to a lot of other useful info on styling DataGrid.

<toolkit:DataGrid Name="DG1" ItemsSource="{Binding}" AutoGenerateColumns="False" AlternationCount="3" AlternatingRowBackground="LightBlue" RowBackground="SkyBlue">

You can get the full code samples (VB and C#) from here.

-Margaret

Comments

  • Anonymous
    April 02, 2009
    Thank you for submitting this cool story - Trackback from DotNetShoutout