Having face this problem myself I came up with a set of styles that could be used to produce grid lines.
There are three main aspects that makes these styles work.
- Line.Stretch is set to fill.
- For horizontal lines the VerticalAlignment of the line is set Bottom, and for VerticalLines the HorizontalAlignment is set to Right.
- The line how many rows or columns to span, this is done by binding to either RowDefinitions or ColumnDefintions Count property.
You can download the full source from here.
EDIT:
Sample updated to display the grid lines at the top and side of the grid.
EDIT:
Sample updated to display the grid lines at the top and side of the grid.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Style x:Key="lineStyle" TargetType="Line"> <Setter Property="Stroke" Value="Gray" /> <Setter Property="Stretch" Value="Fill" /> <Setter Property="Grid.ZIndex" Value="100" /> <Setter Property="StrokeDashArray" Value="1,2" /> </Style> <Style x:Key="horizontalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}"> <Setter Property="X2" Value="1" /> <Setter Property="VerticalAlignment" Value="Bottom" /> <Setter Property="Grid.ColumnSpan" Value="{Binding Path=ColumnDefinitions.Count, RelativeSource={RelativeSource AncestorType=Grid}}"/> </Style> <Style x:Key="verticalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}"> <Setter Property="Y2" Value="1" /> <Setter Property="HorizontalAlignment" Value="Right" /> <Setter Property="Grid.RowSpan" Value="{Binding Path=RowDefinitions.Count, RelativeSource={RelativeSource AncestorType=Grid}}"/> </Style> <Style x:Key="verticalLineStyleLeft" TargetType="Line" BasedOn="{StaticResource verticalLineStyle}"> <Setter Property="HorizontalAlignment" Value="Left" /> </Style> <Style x:Key="horizontalLineStyleTop" TargetType="Line" BasedOn="{StaticResource horizontalLineStyle}"> <Setter Property="VerticalAlignment" Value="Top" /> </Style> </ResourceDictionary>
4 comments:
Thanks for this .. succint explanation..
Nice, but the outer left and outer top lines are missing, any chance to fix this? Thanks :-)
I tryed to do the same issue in silverlight but can`t solve the problem with
RelativeSource={RelativeSource AncestorType=Grid}}
compiler could not find AncestorType property.Maybe you have a solution?
Unfortunately this is a limitation of Silverlight. As of version 4 the RelativeSource markup extension only supports Self and TemplatedParent.
Post a Comment