Или вы можете использовать эту сетку, которую я только что сделал.Это автоматически добавит границу к каждой ячейке в сетке.Это результат:
C #:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace GridWithBorder
{
public class BorderGrid : Grid
{
protected override void OnRender(DrawingContext dc)
{
double leftOffset = 0;
double topOffset = 0;
Pen pen = new Pen(Brushes.Black, 3);
pen.Freeze();
foreach (RowDefinition row in this.RowDefinitions)
{
dc.DrawLine(pen, new Point(0, topOffset), new Point(this.ActualWidth, topOffset));
topOffset += row.ActualHeight;
}
// draw last line at the bottom
dc.DrawLine(pen, new Point(0, topOffset), new Point(this.ActualWidth, topOffset));
//foreach (ColumnDefinition column in this.ColumnDefinitions)
//{
// dc.DrawLine(pen, new Point(leftOffset, 0), new Point(leftOffset, this.ActualHeight));
// leftOffset += column.ActualWidth;
//}
// draw last line on the right
//dc.DrawLine(pen, new Point(leftOffset, 0), new Point(leftOffset, this.ActualHeight));
base.OnRender(dc);
}
}
}
XAML:
<Window x:Class="GridWithBorder.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GridWithBorder"
Title="MainWindow" Height="350" Width="525">
<local:BorderGrid>
<local:BorderGrid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</local:BorderGrid.RowDefinitions>
<local:BorderGrid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</local:BorderGrid.ColumnDefinitions>
<Rectangle Grid.Row="0" Grid.Column="0" Fill="Red" Margin="5" />
<Rectangle Grid.Row="0" Grid.Column="1" Fill="Blue" Margin="5" />
<Rectangle Grid.Row="0" Grid.Column="2" Fill="Orange" Margin="5" />
<Rectangle Grid.Row="0" Grid.Column="3" Fill="Red" Margin="5" />
<Rectangle Grid.Row="1" Grid.Column="0" Fill="Yellow" Margin="5" />
<Rectangle Grid.Row="1" Grid.Column="1" Fill="Green" Margin="5" />
<Rectangle Grid.Row="1" Grid.Column="2" Fill="Purple" Margin="5" />
<Rectangle Grid.Row="1" Grid.Column="3" Fill="Green" Margin="5" />
<Rectangle Grid.Row="2" Grid.Column="0" Fill="Orange" Margin="5" />
<Rectangle Grid.Row="2" Grid.Column="1" Fill="Red" Margin="5" />
<Rectangle Grid.Row="2" Grid.Column="2" Fill="Blue" Margin="5" />
<Rectangle Grid.Row="2" Grid.Column="3" Fill="Red" Margin="5" />
</local:BorderGrid>
</Window>