WPF DataGrid Custommization using Style and Template

转载:http://www.codeproject.com/Articles/586132/WPF-DataGrid-Custommization-using-Style-and-Templa

WPF DataGrid Custommization using Style and Template

WPF DataGrid Custommization using Style and Template
Hiren Khirsaria2 May 2013 CPOL
 
 
customize DataGridRowHeader, DataGridColumnHeader, DataGridCell, DataGridRow styles & templates and change the ScrollBar style in DataGrid
 

Introduction 

In this article we will go though how to change the appearance of the datagrid control.

how to customize template of DataGridColumnHeader, DataGridRow, DataGridCell, DatagridRowHeader and ScrollViewer of the DataGrid.

In this article you can learn, how to expand multiple RowDetailTemplate using  DatagridRowHeader style, 

how to change ScrollBar style in DataGrid.  

Background

DataGrid is a powerful control in WPF. it is used to render collection of data in customization grid.

 WPF DataGrid Custommization using Style and Template




Using the code

DataGridColumnHeader Style  

Default Column Header : 

WPF DataGrid Custommization using Style and Template

 Customize Column Header : 

 WPF DataGrid Custommization using Style and Template

Step 1 : Create style of TargetType=DatagridColumnHeader

 1  <Style TargetType="{x:Type DataGridColumnHeader}">
 2     <Setter Property="VerticalContentAlignment" Value="Center" />
 3     <Setter Property="Height" Value="35" />
 4     <Setter Property="SeparatorBrush" Value="DarkRed" />
 5     <Setter Property="FontWeight" Value="Black" />
 6     <Setter Property="Template">
 7         <Setter.Value>
 8            <!-- Your Template goes here -->        
 9         </Setter.Value>
10     </Setter>
11 </Style> 

 

 

 Step 2 : Create ControlTemplate of TargetType=DatagridColumnHeader and add within Template. 

 1 <ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
 2    <Grid>
 3     <Border x:Name="columnHeaderBorder"
 4         BorderThickness="1"
 5         Padding="3,0,3,0">
 6         <Border.BorderBrush>
 7             <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
 8                 <GradientStop Offset="0" Color="#A5A5A5" />
 9                 <GradientStop Offset="1" Color="#4B4B4B" />
10             </LinearGradientBrush>
11         </Border.BorderBrush>
12         <Border.Background>
13             <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
14                 <GradientStop Offset="0" Color="#DEB40A" />
15                 <GradientStop Offset="1" Color="#FF7F00" />
16             </LinearGradientBrush>
17         </Border.Background>
18        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
19                  VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
20                 SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
21     </Border>
22    </Grid>
23 </ControlTemplate>  

 

 Created border with setting Background color using LinearGradientBrush to set multiple color in linear with specified offset.

LinearGradientBrush has 2 properties

- StartPoint : used to fill color at given point (X and Y).

- EndPoint : gradient color will stop fill to given end point (X and Y)

 ContentPresenter holds the Content (Data/Header Text, etc.) of the DataGridColumn.

 

Step 3: Add VisualState for Change BackgroundColor of DataGridColumn on Mouse Hover.  

 1 <VisualStateManager.VisualStateGroups>
 2    <VisualStateGroup x:Name="CommonStates">
 3     <VisualState x:Name="Normal" />
 4     <VisualState x:Name="MouseOver">
 5        <Storyboard>
 6         <ColorAnimationUsingKeyFrames Storyboard.TargetName="columnHeaderBorder" 
 7 Storyboard.TargetProperty="(Panel.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)">
 8             <EasingColorKeyFrame KeyTime="0" Value="LightYellow" />
 9         </ColorAnimationUsingKeyFrames>
10        </Storyboard>
11     </VisualState>
12    </VisualStateGroup>
13 </VisualStateManager.VisualStateGroups>  

 

VisualStateManager is used for animate control when specific state changed ( Normal, MouseOver, Focus etc.) 

Storyboard is a container timeline that provides object and property targeting information for its child animation. In short all animations are placed within storyboard.

Storyboard has Storyboard.TargetName and Storyboard.TargetProperty attached properties. these properties are used for set specified animation to target property of target control.

ColorAnimationUsingKeyFrames is used to animates the value of a Color property along a set of KeyFrames over a specified Duration. 

In above code, added ColorAnimationUsingKeyFrames to change datagrid columnHeaderBorder control GardientStop[1] Color from #FF7F00 To LightYellow. 

To know more about Animation and Storyboard please read linked post. 

ColorAnimation added within Storyboard to change the color when user mouse over the datagrid column.

DataGridRow Style  

Default Row : 

 WPF DataGrid Custommization using Style and Template

Customize Row : 

WPF DataGrid Custommization using Style and Template

As shown in above 2 figure, first one is default DataGrid style,

second one is customize style with Row Color, Alternate Row Color and Mouse Over Row Color. 

Step 1: Create Style of TargetType=DataGridRow

1 <Style TargetType="{x:Type DataGridRow}">
2     <Setter Property="Background" Value="LightYellow" />        
3     <Setter Property="Validation.ErrorTemplate" Value="{x:Null}" />        
4     <Setter Property="Template">
5         <Setter.Value>
6             <!-- Row Template goes here -->    
7         </Setter.Value>
8     </Setter>
9 </Style> 

 

 In above code, created style for DataGridRow and setting Row Background Property to LightYellow.

Step 2: Create Template for DataGridRow

 1 <Setter Property="Template">
 2    <Setter.Value>
 3     <ControlTemplate TargetType="{x:Type DataGridRow}">
 4        <Border x:Name="DGR_Border"
 5             BorderBrush="{TemplateBinding BorderBrush}"
 6             BorderThickness="{TemplateBinding BorderThickness}"
 7                 SnapsToDevicePixels="True">
 8         <Border.Background>
 9             <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
10                 <GradientStop Offset="0" Color="#AAFFFFAA" />
11                 <GradientStop Offset="1" Color="#AAFFD455" />
12             </LinearGradientBrush>
13         </Border.Background>
14         <SelectiveScrollingGrid>
15            <SelectiveScrollingGrid.ColumnDefinitions>
16             <ColumnDefinition Width="Auto" />
17             <ColumnDefinition Width="*" />
18            </SelectiveScrollingGrid.ColumnDefinitions>
19            <SelectiveScrollingGrid.RowDefinitions>
20             <RowDefinition Height="*" />
21             <RowDefinition Height="Auto" />
22            </SelectiveScrollingGrid.RowDefinitions>
23            <DataGridCellsPresenter Grid.Column="1"
24             ItemsPanel="{TemplateBinding ItemsPanel}"
25             SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
26            <DataGridDetailsPresenter Grid.Row="1"
27             Grid.Column="1"
28             SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding 
29  AreRowDetailsFrozen,
30   ConverterParameter={x:Static SelectiveScrollingOrientation.Vertical},
31               Converter={x:Static DataGrid.RowDetailsScrollingConverter},
32               RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
33             Visibility="{TemplateBinding DetailsVisibility}" />
34            <DataGridRowHeader Grid.RowSpan="2"
35             SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"
36             Visibility="{Binding HeadersVisibility,
37 ConverterParameter={x:Static DataGridHeadersVisibility.Row},
38    Converter={x:Static DataGrid.HeadersVisibilityConverter},
39     RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
40         </SelectiveScrollingGrid>
41         </Border>
42     </ControlTemplate>
43    </Setter.Value>
44 </Setter>  

 

 In above code, DataGridRow ControlTemplate contains DataGridCellPresenter, DataGridDetailsPresenter and DataGridRowHeader.

Keep all these Presenter as it is.

we need to just change the main border background color,

Set the Border (DGR_Border)  background color as LinerGradientBrush with combination of Yellow and rad.

so each row is highlighted with this background color in grid.

 

Step 3: Now, Add VisualState for Setting DataGridRow Background color for Alternate Row, MouseOver Row and Selected Row. 

For setting alternate row color, first we need to set AlternationCount property value to 2 in the DataGrid. 

1  <DataGrid Name="dataGrid1"
2     AlternationCount="2"   />  

 

Then, Add VisualStates (AlternatingRow, MouseOver and Selected Row) 

 1 <VisualStateManager.VisualStateGroups>
 2    <VisualStateGroup x:Name="CommonStates">
 3     <VisualState x:Name="Normal" />
 4     <VisualState x:Name="Normal_AlternatingRow">
 5        <Storyboard>
 6         <ColorAnimationUsingKeyFrames Storyboard.TargetName="DGR_Border" 
 7 Storyboard.TargetProperty="(Panel.Background).(GradientBrush.GradientStops)[0].(GradientStop.Color)">
 8             <EasingColorKeyFrame KeyTime="0" Value="#AAF0C570" />
 9         </ColorAnimationUsingKeyFrames>
10         <ColorAnimationUsingKeyFrames Storyboard.TargetName="DGR_Border" 
11 Storyboard.TargetProperty="(Panel.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)">
12             <EasingColorKeyFrame KeyTime="0" Value="#AAFF7F00" />
13         </ColorAnimationUsingKeyFrames>
14        </Storyboard>
15     </VisualState>
16     <VisualState x:Name="Normal_Selected">
17        <Storyboard>
18         <!-- ColorAnimation here same as Normal_AlternatingRow state -->
19        </Storyboard>
20     </VisualState>
21     <VisualState x:Name="MouseOver">
22        <Storyboard>
23         <!-- ColorAnimation here same as Normal_AlternatingRow state -->
24        </Storyboard>
25     </VisualState>
26    </VisualStateGroup>
27 </VisualStateManager.VisualStateGroups>  

 

 To change Alternate row color, visualstatemanager provides Normal_AlternatingRow  visual state for datagrid row.

In above code snippet, Three VisualState added

one for AlternateRow, one for MouseOverRow and one for SelectedRow. 

All have ColorAnimation, that changes  DGR_Border control Background‘s GradientStop[0] & GradientStop[1] color on specific state change. 

  

DataGridCell Style  

I have created this style for hide the default datagrid row selected color (Blue). 

Because even setting DataGridRow selected color, it doesn‘t affect on UI, DataGridCell default style will overwrite background color to its default one.       

 1 <Style TargetType="{x:Type DataGridCell}">
 2    <Setter Property="Template">
 3     <Setter.Value>
 4        <ControlTemplate TargetType="{x:Type DataGridCell}">
 5         <Border x:Name="border"
 6             Background="Transparent"
 7             BorderBrush="Transparent"
 8             BorderThickness="1"
 9             SnapsToDevicePixels="True">
10                         
11            <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
12         </Border>
13        </ControlTemplate>
14     </Setter.Value>
15    </Setter>
16 </Style>  

 

In above code, i have set child as ConentPresenter wihtin Border control, and Border control is placed in ControlTemplate root.

I sets Border control Background and BorderBrush to Transparent, so DatGridCell background is hided. 

Now, selected row style will applied from DataGridRow Selected VisualSate.  

DataGrid RowDetail Template

 WPF DataGrid Custommization using Style and Template

Step 1: Create DataTemplate for RowDetails 

 1 <DataTemplate x:Key="RowDetailTemplate">
 2    <Grid x:Name="RowDetailGrid"
 3      Width="470"
 4      Height="Auto"
 5      Margin="5">
 6     <Border HorizontalAlignment="Left"
 7         VerticalAlignment="Top"
 8         CornerRadius="5">
 9         <Border.Background>
10             <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
11                 <GradientStop Offset="0" Color="WhiteSmoke" />
12                 <GradientStop Offset="0.75" Color="#AAFFFFAA" />
13                 <GradientStop Offset="1" Color="#AAFFD455" />
14             </LinearGradientBrush>
15         </Border.Background>
16         <Grid>
17         <Grid.RowDefinitions>
18                 <RowDefinition Height="Auto" />
19                 <RowDefinition Height="*" />
20             </Grid.RowDefinitions>
21             <TextBlock Grid.Row="0"
22                    Margin="10"
23                    HorizontalAlignment="Center"
24                    FontSize="18"
25                    FontWeight="Black"
26                    Text="Temperature Description" />
27             <TextBlock Grid.Row="1"
28                    Margin="10"
29                    HorizontalAlignment="Left"
30                    Text="{Binding Description}"
31                    TextWrapping="WrapWithOverflow" />
32         </Grid>
33     </Border>
34     <Border Margin="0 0 8 0" CornerRadius="5">
35         <Border.Background>
36             <RadialGradientBrush Center="0.5,1" GradientOrigin="0,1" 
37      Opacity="0.3" RadiusX="0.8" RadiusY="0.8">
38                 <GradientStop Offset="1" Color="#AAFFD455" />
39                 <GradientStop Offset="1" Color="WhiteSmoke" />
40             </RadialGradientBrush>
41         </Border.Background>
42     </Border>
43    </Grid>
44 </DataTemplate>   

 

In above code, Two Border controls are placed within grid.

In First Border Backgroud is set with LinearGradientBrush, Data binded for display in RowDetails Panel.

In Second Birder Background is set with RadialGradientBrush to put a light cirlce on top of the Detail Panel as show in above image (Color around Temperature Description Text in RowDetail Panel). 

Below image will describes how RadialGradient works (Fill the color). 

WPF DataGrid Custommization using Style and Template 

  

Step 2: Create ToggleButon style for Show/Hide RowDetail Panel.

 

 

 

 1  <Style TargetType="ToggleButton">
 2         <Setter Property="Padding" Value="3" />
 3         <Setter Property="Template">
 4             <Setter.Value>
 5                 <ControlTemplate TargetType="ToggleButton">
 6                     <Grid>
 7                         
 8                         <ContentPresenter x:Name="contentPresenter"
 9                                           Margin="{TemplateBinding Padding}"
10                                           HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
11                                           VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
12                                           Content="{TemplateBinding Content}"
13                                           ContentTemplate="{TemplateBinding ContentTemplate}" />
14                         <Path x:Name="DefaultPath"
15                               VerticalAlignment="Top"
16                               Data="M0,0 14,7 0,14 Z"
17                               Fill="Gray"
18                               Stretch="Fill" />
19                         <Path x:Name="CheckedPath"
20                               VerticalAlignment="Top"
21                               Data="M0,0 14,0 7,14 Z"
22                               Fill="LightGray"
23                               Stretch="Fill"
24                               Visibility="Collapsed" />
25                     </Grid>
26                 </ControlTemplate>
27             </Setter.Value>
28         </Setter>
29     </Style>      

 

Created Two Shapes using path, one for Collapsed RowDetail Panel, one for Expand RowDetail Panel. 

WPF DataGrid Custommization using Style and Template    WPF DataGrid Custommization using Style and Template

Path is used to create shapes or graphic objects like Triange, Hexagone, Ellipse, etc,  Path is inherited from Shape class.

you can also draw a picture using path. you can Fill shape with color using Fill property.




Step 3: Add VisualState for Change Path on Checked/Unchecked State.

 1 <VisualStateManager.VisualStateGroups>
 2    <VisualStateGroup x:Name="CheckStates">
 3     <VisualState x:Name="Checked">
 4        <Storyboard>
 5         <ObjectAnimationUsingKeyFrames Duration="0"
 6                                   Storyboard.TargetName="DefaultPath"
 7                                    Storyboard.TargetProperty="Visibility">
 8             <DiscreteObjectKeyFrame KeyTime="0">
 9                 <DiscreteObjectKeyFrame.Value>
10                     <Visibility>Collapsed</Visibility>
11                 </DiscreteObjectKeyFrame.Value>
12             </DiscreteObjectKeyFrame>
13         </ObjectAnimationUsingKeyFrames>
14         <ObjectAnimationUsingKeyFrames Duration="0"
15                                Storyboard.TargetName="CheckedPath"
16                                Storyboard.TargetProperty="Visibility">
17             <DiscreteObjectKeyFrame KeyTime="0">
18                 <DiscreteObjectKeyFrame.Value>
19                     <Visibility>Visible</Visibility>
20                 </DiscreteObjectKeyFrame.Value>
21             </DiscreteObjectKeyFrame>
22         </ObjectAnimationUsingKeyFrames>
23         <ColorAnimationUsingKeyFrames Storyboard.TargetName="CheckedPath" 
24 Storyboard.TargetProperty="(Path.Fill).(SolidColorBrush.Color)">
25             <SplineColorKeyFrame KeyTime="0:0:0.2" Value="#CCAA0000" />
26         </ColorAnimationUsingKeyFrames>
27        </Storyboard>
28     </VisualState>
29     <VisualState x:Name="Unchecked" />
30    </VisualStateGroup>
31 </VisualStateManager.VisualStateGroups>

 

The ObjectAnimationUsingKeyFrames animation allows you to use object instead of primitive values for your animation keyframes.

The only DiscreteObjectkeyframes keyframe allowed in the ObjectAnimationUsingKeyFrames animation.

In above code, Visiblity of Expand/Collapsed Path is changed using ObjectAnimationUsingKeyFrames on CheckedVisualState.

On Checked State of ToggleButton Expanded Path‘s color changed using ColorAnimationUsingKeyFrames.




SplineColorKeyFrame is used to animates from the Color value of the previous key frame to its own Value using splined interpolation. it creates a variable transition between values which is determined by the KeySpline property.

Step 4: Set RowDetailTemplate in DataGrid and Add ToggleButton in RowHeaderTemplate. 

 1 <DataGrid Name="dataGrid1"                 
 2     Margin="10"
 3     HorizontalAlignment="Left"
 4     VerticalAlignment="Top"
 5     AlternationCount="2"                 
 6     MinRowHeight="26"
 7     RowDetailsTemplate="{StaticResource RowDetailTemplate}" >
 8     <DataGrid.RowHeaderTemplate>
 9         <DataTemplate>
10             <ToggleButton x:Name="RowHeaderToggleButton"
11                 Click="ToggleButton_Click"
12                 Cursor="Hand" />
13         </DataTemplate>
14     </DataGrid.RowHeaderTemplate>
15 </DataGrid>    

 

 I have set RowDetailTemplate as StaticResource because DataTemplate is created in same page. if DataTemplate or Style is placed in ResourceDictionary then you have to set Style using DynamicResource.

To add ToggleButton in every row header, you need to set RowHeaderTemplate, as shown in above source, ToggleButton control is set in DataTemplate of DataGrid RowHeaderTemplate.

it will show triangle image (created using path) on every row header like :

WPF DataGrid Custommization using Style and Template

 Now, we need to Expand RowDetail on click of Triangle or we can say on TogggleButton checked

Step 5: Handle ToggleButton click event to Expand/Collapsed RowDetail

First you have to set one property in DataGrid Style for change RowDetail Visibility on DataGridRow selected

 

1    <Style TargetType="{x:Type DataGrid}">        
2         <Setter Property="RowDetailsVisibilityMode" Value="VisibleWhenSelected" />  

 

This will set RowDetailVisibilityMode to Visible when perticular DataRow is selected.

 

 1 private void ToggleButton_Click(object sender, RoutedEventArgs e)
 2 {
 3     DependencyObject obj = (DependencyObject)e.OriginalSource;
 4     while (!(obj is DataGridRow) && obj != null) obj = VisualTreeHelper.GetParent(obj);
 5     if (obj is DataGridRow)
 6     {
 7         if ((obj as DataGridRow).DetailsVisibility == Visibility.Visible)
 8         {                    
 9             (obj as DataGridRow).IsSelected = false;
10         }
11         else
12         {                    
13             (obj as DataGridRow).IsSelected = true;
14         }
15     }
16 } 

 

 In ToggleButton click event, first find current datagrid row of selected togglebutton usingVisualTreeHelper.GerParent method.

VisualTreeHelper is used to perform task involving nodes in visual tree.

GetParent method will Returns a DependencyObject value that represents the parent of the visual object.

Now, set the DataGridRow IsSelected property based on ToggleButton checked state and DataGridRow.DetailsVisibility.

 

 Step 6:  Add Event Handler - RowDetailsVisibilityChanged to manage ToggleButton checked state 

 

 

1 <DataGrid Name="dataGrid1"                
2     RowDetailsVisibilityChanged="dataGrid1_RowDetailsVisibilityChanged"> 

 

 - Create Method in .CS file that will find FrameworkElement by name from Parent DependencyObject.

 1 public static FrameworkElement GetTemplateChildByName(DependencyObject parent, string name)
 2 {
 3     int childnum = VisualTreeHelper.GetChildrenCount(parent);
 4     for (int i = 0; i < childnum; i++)
 5     {
 6         var child = VisualTreeHelper.GetChild(parent, i);
 7         if (child is FrameworkElement && ((FrameworkElement)child).Name == name)
 8         {
 9             return child as FrameworkElement;
10         }
11         else
12         {
13             var s = GetTemplateChildByName(child, name);
14             if (s != null)
15                 return s;
16         }
17     }
18     return null;
19 }  

 

Above method will iterate through all children available in Parent DependencyObject and return child control by its name. This mehod is recursive method, it will call method itself until child control found or up to last child element whatever is first.

if child element not found, it will iterate till last child element and return null value. 

VisualTreeHelper.GetChild method will find first child in Visual Tree.  

 - Create DataGrid RowDetailsVisibilityChanged Event Handler  

 1 private void dataGrid1_RowDetailsVisibilityChanged(object sender,DataGridRowDetailsEventArgs e)
 2 {
 3     DataGridRow row = e.Row as DataGridRow;
 4     FrameworkElement tb = GetTemplateChildByName(row, "RowHeaderToggleButton");
 5     if (tb != null)
 6     {
 7         if (row.DetailsVisibility == System.Windows.Visibility.Visible)
 8         {
 9             (tb as ToggleButton).IsChecked = true;
10         }
11         else
12         {
13             (tb as ToggleButton).IsChecked = false;
14         }
15     }
16  
17 }   

 

 Above method will find ToggleButton from Selected DataGridRow Template.

If ToggleButton found then, set its IsChecked property to true if  DataGridRow DetailsVisibility=Visible

otherwise set IsChecked  property to false.

this method is only for the purpose of change the Expand/Collapsed Path(Shape)  based on row detail visibility changed. 

 

DataGrid ScrollBar Style

WPF DataGrid Custommization using Style and Template

   

Step 1 : Create Repeat Button Style 

 1 <Style x:Key="ScrollButtons" TargetType="{x:Type RepeatButton}">
 2     <Setter Property="Template">
 3         <Setter.Value>
 4             <ControlTemplate TargetType="{x:Type RepeatButton}">
 5                 <Border Name="Border" Background="Transparent">
 6                      <ContentPresenter />
 7                 </Border>
 8             </ControlTemplate>
 9         </Setter.Value>
10     </Setter>
11 </Style>    

 

 Change the Repeat Button Template to remove default style.

Added Border control within ControlTemplate and set Background to Transparent. now placeContentPresenter within Border,

ContentPresenter is used to displays the content of ContentControl.

when you going to customize the template of control do not forget to put ContentPresenter within Template otherwise your data will not display. 

 Step 2 : Create Required Brushes and Color Resources 

 1 <Color x:Key="BackgroundColor">#AE2F33</Color>
 2 <Color x:Key="StandardColor">#800000</Color>
 3 <Color x:Key="HoverColor">#AAC64D45</Color>
 4 <Color x:Key="PressedColor">#AA0000</Color>
 5 <Color x:Key="DialogBackgroundColor">#FF666666</Color>
 6 <Color x:Key="ScollBarBackgroundStart">#77C64D45</Color>
 7 <Color x:Key="ScollBarBackgroundEnd">#99C64D45</Color>
 8 <SolidColorBrush x:Key="StandardBrush" Color="{StaticResource StandardColor}" />
 9 <SolidColorBrush x:Key="HoverBrush" Color="{StaticResource HoverColor}" />
10 <SolidColorBrush x:Key="BackgroundBrush" Color="{StaticResource BackgroundColor}" />
11 <LinearGradientBrush x:Key="ScollBarBackgroundBrush" StartPoint="0,0" EndPoint="1,0">
12     <LinearGradientBrush.GradientStops>
13         <GradientStop Offset="0" Color="{StaticResource ScollBarBackgroundStart}" />
14         <GradientStop Offset="1" Color="{StaticResource ScollBarBackgroundEnd}" />
15     </LinearGradientBrush.GradientStops>
16 </LinearGradientBrush>   

 

WPF provides following different types of brushes : 

- SolidColorBrush : will paints an area with solid color. 

- LinearGradientBrush : will paints an area with linear gradient . 

- RadialGradientBrush : will Paints an area with a radial gradient. A focal point defines the beginning of the gradient, and a circle defines the end point of the gradient. 

- ImageBrush : will paint an area with image. 

- DrawingBrush : Paints an area with a System.Windows.Media.Drawing, which can include shapes,text, video, images, or other drawings. 

Brushes are used to Fill/Paint objects/FrameworkElements with Graphics/Colors.

I have created brushes for Default, Hover and Pressed state of ScrollBars. 

 

Step 3: Create  ScrollBar Thumb Style    

 1 <Style x:Key="ScrollThumbs" TargetType="{x:Type Thumb}">
 2     <Setter Property="Background" Value="{StaticResource BackgroundBrush}" />
 3     <Setter Property="Template">
 4         <Setter.Value>
 5            <ControlTemplate TargetType="{x:Type Thumb}">
 6                 <Grid Name="Grid">                    
 7                     <Rectangle Name="Rectangle1"
 8                          Width="7"
 9                          Height="Auto"
10                          HorizontalAlignment="Stretch"
11                          VerticalAlignment="Stretch"
12                          Fill="{TemplateBinding Background}"
13                          RadiusX="4"
14                          RadiusY="4" />
15                 </Grid>            
16            </ControlTemplate>
17         </Setter.Value>
18     </Setter>
19 </Style> 

 

 Created style of TargetType=Thumb, it will apply Thumb style in scrollbar by setting Style to StaticResource/DynamiceResource. 

Added Rectangle control within ControlTemplate and setting Fill property to  {TemplateBinding Background} , this TemplateBinding will bind color from Control Background, so it will set Rectangle Fill color to  BackgroundBrush  ( <Setter Property="Background" Value="{StaticResource BackgroundBrush}" />) 

 

Step 4: Create  ScrollBar Style 

 

 1 <Style x:Key="MyScrollBar" TargetType="{x:Type ScrollBar}">
 2    <Setter Property="Background" Value="{DynamicResource ScollBarBackgroundBrush}" />
 3    <Setter Property="Width" Value="12" />
 4    <Setter Property="Template">
 5     <Setter.Value>
 6        <ControlTemplate TargetType="{x:Type ScrollBar}">
 7           <Grid x:Name="GridRoot"
 8            Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidth}}"
 9             Background="{TemplateBinding Background}">
10         <Grid.RowDefinitions>
11             <RowDefinition MaxHeight="18" />
12             <RowDefinition Height="0.00001*" />
13             <RowDefinition MaxHeight="18" />
14         </Grid.RowDefinitions>
15         <RepeatButton x:Name="DecreaseRepeat"
16             Command="ScrollBar.LineUpCommand"
17             Foreground="{StaticResource StandardBrush}"
18             Style="{DynamicResource ScrollButtons}">
19                 <Path x:Name="DecreaseArrow"
20                     HorizontalAlignment="Center"
21                     VerticalAlignment="Center"
22                     Data="F1 M 3.5,0L 0,7L 7,7L 3.5,0 Z "
23                     Fill="{StaticResource StandardBrush}" />
24         </RepeatButton>
25         <Track x:Name="PART_Track"
26             Grid.Row="1"
27             Focusable="false"
28             IsDirectionReversed="true">
29             <Track.Thumb>
30                 <Thumb x:Name="Thumb"
31                     Background="{DynamicResource ButtonDefaultBrush}"
32                     Style="{DynamicResource ScrollThumbs}" />
33             </Track.Thumb>            
34         </Track>
35         <RepeatButton x:Name="IncreaseRepeat"
36             Grid.Row="2"
37             Command="ScrollBar.LineDownCommand"
38             Foreground="{DynamicResource StandardBrush}"
39             Style="{DynamicResource ScrollButtons}">
40                 <Path x:Name="IncreaseArrow"
41                     HorizontalAlignment="Center"
42                     VerticalAlignment="Center"
43                     Data="F1 M 3.5,7L 7,0L 0,0L 3.5,7 Z "
44                     Fill="{StaticResource StandardBrush}" />
45         </RepeatButton>
46            </Grid>                    
47        </ControlTemplate>
48     </Setter.Value>
49    </Setter>
50 </Style> 

 

In ScollBar ControlTemplate, Two Repeat Buttons (one for Top, one for Bottom) and Thumb is added.

For Top RepeatButton you have to set Command to  ScrollBar.LineUpCommand and set Style={DynamicResource ScrollButtons} previously created in ResourceDictionary.

Create Shape for Top Button using Path and Put wihtin RepeatButton. 

 Same way, for Bottom RepeatButton you have to set Command to  ScrollBar.LineDownCommand  as set same style as top button.

Create Track and add Thumb to Track.Thumb. Set Previously created Thumb style to Track.Thumb. 

Track Represents a control primitive that handles the positioning and sizing of a System.Windows.Controls.Primitives. Thumb control used to set a Primitives.Track.Value 

 

Step 5 : Add Trigger for RepeatButton and Thumb to change color on MouseOver and Pressed Property changed. 

 1 <ControlTemplate.Triggers>
 2     <Trigger SourceName="IncreaseRepeat" Property="IsMouseOver" Value="true">
 3         <Setter TargetName="IncreaseArrow" Property="Fill" 
 4                         Value="{StaticResource HoverBrush}" />
 5         </Trigger>        
 6     <Trigger SourceName="Thumb" Property="IsMouseOver" Value="true">
 7         <Setter TargetName="Thumb" Property="Background" 
 8                          Value="{StaticResource HoverBrush}" />
 9     </Trigger>
10     <Trigger SourceName="Thumb" Property="IsDragging" Value="true">
11         <Setter TargetName="Thumb" Property="Background" 
12                         Value="{StaticResource StandardBrush}" />
13     </Trigger>
14 </ControlTemplate.Triggers> <span style="font-size: 9pt;"> </span> 

 

In above example, i have created MouseOver trigger for RepeatButton to change Fill porperty.

For Thumb 2 trigger is created, one for MouseOver and one for Dragging to change Thumb Background Property. 

you can create trigger on other property also (like : Press, Enable etc.)

Step 6 : Last, Set ScrollBar style in DataGrid Tempalate. 

 1 <ControlTemplate TargetType="{x:Type DataGrid}">
 2    <ScrollViewer x:Name="DG_ScrollViewer" Focusable="false">
 3     <ScrollViewer.Template>
 4         <ControlTemplate TargetType="{x:Type ScrollViewer}">
 5             <Grid>
 6              <!--your DataGridColumnHeadersPresenter,ScrollContentPresenter -->                 <ScrollContentPresenter x:Name="PART_ScrollContentPresenter"
 7                    Grid.Row="1"
 8                    Grid.ColumnSpan="2"
 9                    CanContentScroll="{TemplateBinding CanContentScroll}" />
10                 <ScrollBar x:Name="PART_VerticalScrollBar"
11                     Maximum="{TemplateBinding ScrollableHeight}"
12                     Orientation="Vertical"
13                     Style="{DynamicResource MyScrollBar}"
14                     ViewportSize="{TemplateBinding ViewportHeight}" />
15                                <ScrollBar x:Name="PART_HorizontalScrollBar"                                            Maximum="{TemplateBinding ScrollableWidth}" 
16                                        Orientation="Horizontal" 
17                                        ViewportSize="{TemplateBinding ViewportWidth}" /> 
18                 </ControlTemplate> 
19          <ScrollViewer.Template>
20          <ItemPresenter />
21    </ScrollViewer>  
22 </ControlTemplate >  

 

Two ScrollBars added within ScrollViewer in DataGrid ControlTemplate.

one for vertical and one for horizontal scroll. set Style to  {DynamicResource MyScrollBar} as previously created scrollbar style.

In this post I tried to include all points for fully customize DataGrid style to change the appearance and look of the control. 

 

Points of Interest

During Development question arise in mind that how to show mutliple RowDetails Panels and Show/Hide RowDetail Panel when we needed.

for that, I have Crated ToggleButton and added in RowHeaderTemplate of DataGrid, on Click on ToggleButton show the RowDetails and again on Click Hide the Detail Panel. 

 I have implemented change related to Show/Hide RowDetail Panel in this post also. that is the new thing in DataGrid. 

History

 

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

WPF DataGrid Custommization using Style and Template
Hiren Khirsaria
Software Developer (Senior) 
India WPF DataGrid Custommization using Style and Template
has Total 5+ years of Experience in Microsoft.Net Environment. out of that,
 
2 + year of Excperience in .Net Development with C# and SQL Server 2005/2008.
 
3 + years of Experience in WPF/Silverlight.
 
Current area of Development in Mono for Android (Xamarin), Silverlight/ WPF and Windows Phone 7 Application.
 
Follow him on : http://hirenkhirsaria.blogspot.com/

 

WPF DataGrid Custommization using Style and Template

上一篇:IE 中创建 子窗口 传值 与接收值 【window.showModalDialog】


下一篇:关于C# 在TXT写入数据使用UTF-8 bom编码模式